Home  >  Article  >  Backend Development  >  python中__call__内置函数用法实例

python中__call__内置函数用法实例

WBOY
WBOYOriginal
2016-06-10 15:10:521322browse

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

对象通过提供__call__(slef, [,*args [,**kwargs]])方法可以模拟函数的行为,如果一个对象x提供了该方法,就可以像函数一样使用它,也就是说x(arg1, arg2...) 等同于调用x.__call__(self, arg1, arg2)。模拟函数的对象可以用于创建仿函数(functor) 或代理(proxy)

class DistanceForm(object):
  def __init__(self, origin):
    self.origin = origin
    print "origin :"+str(origin)
  def __call__(self, x):
    print "x :"+str(x)
p = DistanceForm(100)
p(2000)

输出:

>>> 
origin :100
x :2000

希望本文所述对大家的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