python中__call__方法示例分析

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助

相关文章

使用Python的内建模块collections的教程

collections是Python内建的一个集合模块,提供了许多有用的集合类。 namedtuple 我们知道tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成: &g...

Python 根据数据模板创建shapefile的实现

废话不多说,我就直接上代码让大家看看吧! #!/usr/bin/env python # -*- coding: utf-8 -*- # @File : copyShapefile....

Django ManyToManyField 跨越中间表查询的方法

1、在 django 表中用到了 manytomany 生成了中间表 pyclub_article_column from django.db import models # Cr...

django最快程序开发流程详解

django最快程序开发流程详解

1.建立工程 在工程目录下打开cmd,输入以下命令。其中mysite是项目名称。 django-admin startproject mysite 命令运行完后,在该目录下会出现...

Python自动连接ssh的方法

本文实例讲述了Python自动连接ssh的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/python #-*- coding:utf-8 -*- import...