[Python小菜]__call__是什么

python2.73

python函数中有个叫做闭包的用法,其实还有一种类操作中类似闭包的效果
>>> class A:
...     pass
...
>>> a = A
>>> a
<class __main__.A at 0x02BEC500>
>>> b = A()
>>> b
<__main__.A instance at 0x02C1BBE8>
>>> type(a)     
<type 'classobj'>  #a是class对象
>>> type(b)
<type 'instance'>  #b是class实例
>>> a()
<__main__.A instance at 0x02C15800>  #加了一个括号就是实例化对象
>>> b()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: A instance has no __call__ method #对象调用就出现了一个__call__


??? 这个call是什么呢,实例一般只能调用方法或者属性 A.b的形式
a()当然就不对了,Python却是可以让类实例也可以变成类似方法的直接调用

看下文档中的解释 
Class instances are described below. Class instances are callable only when the class has a __call__() method; x(arguments) is a shorthand for x.__call__(arguments)

当一个类实现了__call__方法后就可以被调用了 
那好,试试看

>>> class B:
...     def __call__(self):
...         print 'hi'
...
>>> B()
<__main__.B instance at 0x02C15E18>
>>> B()()  #生成一个实例,并调用自身
hi
>>> b=B()
>>> b()
hi


但是到底有什么好吃也不太懂。你发现stackoverflow很多人也问到关于这个的问题,
那找找看看别人的说法吧。
在thinking in 各种语言的作者Bruce Eckel的博客里找到这么一点
可以去看看 http://www.artima.com/weblogs/viewpost.jsp?thread=240845
说的是用 __call__的class作为无参数装饰器 

class decoratorWithoutArguments(object):

    def __init__(self, f):
        """
        If there are no decorator arguments, the function
        to be decorated is passed to the constructor.
        """
        print "Inside __init__()"
        self.f = f

    def __call__(self, *args):
        """
        The __call__ method is not called until the
        decorated function is called.
        """
        print "Inside __call__()"
        self.f(*args)
        print "After self.f(*args)"

@decoratorWithoutArguments
def sayHello(a1, a2, a3, a4):
    print 'sayHello arguments:', a1, a2, a3, a4

print "After decoration"
#这种装饰器会在__init__会被调用一次,每次调用时候都会调用__call__
print "Preparing to call sayHello()"
sayHello("say", "hello", "argument", "list")
print "After first sayHello() call"
sayHello("a", "different", "set of", "arguments")
print "After second sayHello() call"




 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值