python中__call__方法示例分析

WBOY
Release: 2016-06-16 08:41:13
Original
1132 people have browsed it

本文实例讲述了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()
Copy after login

执行结果:
没有重写__call__:

>>> from test import CallTest init >>> t = CallTest() init >>> callable(t) False >>> t() Traceback (most recent call last): File "", line 1, in  AttributeError: CallTest instance has no __call__ method >>>
Copy after login

重写__call__:

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

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

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!