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

來源:互聯網
上載者:User

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

英文文檔:

staticmethod(function)

Return a static method for function.

A static method does not receive an implicit first argument.

The @staticmethod 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.

 

說明:

  1. 函數功能時將一個函數,變成類的一個靜態方法。

>>> class Student(object):    def __init__(self,name):        self.name = name    def sayHello(lang):        print(lang)        if lang == 'en':            print('Welcome!')        else:            print('你好!')    staticmethod(sayHello)    >>> Student.sayHello<function Student.sayHello at 0x02AC7810>>>> a = Student('Bob')>>> a.sayHello<bound method Student.sayHello of <__main__.Student object at 0x02AD03F0>>

  2. 靜態方法即可以被類調用,也可以被類的執行個體對象調用。

>>> Student.sayHello('en') # 類調用的時候,將'en'傳給了lang參數enWelcome!>>> a.sayHello() # 類執行個體對象調用的時候,將對象本身傳給了lang參數<__main__.Student object at 0x02AD03F0>你好!

  3. 將一個方法定義成類的靜態方法,正確的方法是使用 @staticmethod裝飾器,這樣在執行個體對象調用的時候,不會把執行個體對象本身傳入靜態方法的第一個參數了。

# 使用裝飾器定義靜態方法>>> class Student(object):    def __init__(self,name):        self.name = name    @staticmethod    def sayHello(lang):        print(lang)        if lang == 'en':            print('Welcome!')        else:            print('你好!')            >>> Student.sayHello('en') #類調用,'en'傳給了lang參數enWelcome!>>> b = Student('Kim') #類執行個體對象調用,不再將類執行個體對象傳入靜態方法>>> b.sayHello()Traceback (most recent call last):  File "<pyshell#71>", line 1, in <module>    b.sayHello()TypeError: sayHello() missing 1 required positional argument: 'lang'>>> b.sayHello('zh')  #類執行個體對象調用,'zh'傳給了lang參數zh你好!

 

聯繫我們

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