[Python小菜]__call__是什麼

來源:互聯網
上載者:User
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"
 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.