python中的__call__允许程序员创建可调用的对象(实例),默认情况下, __call__()方法是没有实现的,这意味着大多数实例是不可调用的。然而,如果在类定义中覆盖了这个方法,那么这个类的实例就成为可调用的。
test.py文件如下:
#!/usr/bin/python# filename:test.py class calltest(): def __init__(self): print 'init' def __call__(self): print 'call' call_test = calltest()
执行结果:
没有重写__call__:
>>> from test import calltestinit>>> t = calltest()init>>> callable(t)false>>> t()traceback (most recent call last): file , line 1, in attributeerror: calltest instance has no __call__ method>>>
重写__call__:
>>> from test import calltestinit>>> t = calltest()init>>> callable(t)true>>> t()call>>>
希望本文所述对大家的python程序设计有所帮助
