python面向对象代码示例

以python2.7为例说明

【示例一】指定调用哪个类实例的函数

>>> class Foo(object):
        def func(self):
            print "foo's function"

>>> class Bar(Foo):
        def func(self):
            print "bar's function"

>>> obj = Bar()
>>> # this will call Bar's function
>>> obj.func()
bar's function
>>> obj.__class__ = Foo  # 指定该对象所属的类
>>> obj.func()
foo's function
>>> 

【示例二】直接调用类的实例,而不是调用实例的方法

>>> class Hi(object):
        def __init__(self, x, y):
            self.__x = x
            self.__y = y
        def myfunc(self):
            print "x=", self.__x, "b=", self.__y

>>> h = Hi("good", "job")
>>> h.myfunc()  # 此处调用该实例的方法
x= good b= job
>>> h("ok")   # 无法直接调用此类的实例
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-d4380afdeffd> in <module>()
----> 1 h("ok")

TypeError: 'Hi' object is not callable
>>> # 如何能直接调用实例?这里有个关键的方法__call__()能实现此类的实例可直接调用
>>> class Hi(object):
        def __init__(self, x, y):
            self.__x = x
            self.__y = y
        def myfunc(self):
            print "x=", self.__x, "b=", self.__y
        def __call__(self, arg):
            print "call:", arg + self.__x + self.__y

>>> h2 = Hi("nice", "guy")
>>> h2.myfunc()
x= nice b= guy
>>> h2("yeah~")    # __call__ 函数能实现此类的实例可直接调用
call: yeah~niceguy

好了,就写到这里,看官们觉得涨知识了,请在文章左侧点个赞 _

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值