Python內建函數(11)——classmethod,pythonclassmethod

來源:互聯網
上載者:User

Python內建函數(11)——classmethod,pythonclassmethod

英文文檔:

classmethod(function)

Return a class method for function.

A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

class C:    @classmethod    def f(cls, arg1, arg2, ...): ...

The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.

Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.

 

說明:

  1. classmethod 是一個裝飾器函數,用來標示一個方法為類方法

  2. 類方法的第一個參數是類對象參數,在方法被調用的時候自動將類對象傳入,參數名稱約定為cls

  3. 如果一個方法被標示為類方法,則該方法可被類對象調用(如 C.f()),也可以被類的執行個體對象調用(如 C().f())

>>> class C:    @classmethod    def f(cls,arg1):        print(cls)        print(arg1)        >>> C.f('類對象調用類方法')<class '__main__.C'>類對象調用類方法>>> c = C()>>> c.f('類執行個體對象調用類方法')<class '__main__.C'>類執行個體對象調用類方法

  4. 類被繼承後,子類也可以調用父類的類方法,但是第一個參數傳入的是子類的類對象

>>> class D(C):    pass>>> D.f("子類的類對象調用父類的類方法")<class '__main__.D'>子類的類對象調用父類的類方法

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.