Home >Backend Development >Python Tutorial >python中__call__方法示例分析

python中__call__方法示例分析

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-16 08:41:131254browse

本文实例讲述了python中__call__方法的用法,分享给大家供大家参考。具体方法分析如下:

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 CallTest
init
>>> t = CallTest()
init
>>> callable(t)
False
>>> t()
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: CallTest instance has no __call__ method
>>>

重写__call__:

>>> from test import CallTest
init
>>> t = CallTest()
init
>>> callable(t)
True
>>> t()
call
>>>

希望本文所述对大家的Python程序设计有所帮助

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn