以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
好了,就写到这里,看官们觉得涨知识了,请在文章左侧点个赞 _