python2.73python函數中有個叫做閉包的用法,其實還有一種類操作中類似閉包的效果
>>> 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)"@decoratorWithoutArgumentsdef sayHello(a1, a2, a3, a4): print 'sayHello arguments:', a1, a2, a3, a4print "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"