Python基于staticmethod裝飾器標(biāo)示靜態(tài)方法
英文文檔:
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.
標(biāo)示方法為靜態(tài)方法的裝飾器
說(shuō)明:
1. 類中普通的方法,實(shí)際上既可以被類直接調(diào)用也可以被類的實(shí)例對(duì)象調(diào)用,但是被實(shí)例對(duì)象調(diào)用的時(shí)候,要求方法至少有一個(gè)參數(shù),而且調(diào)用時(shí)會(huì)將實(shí)例對(duì)象本身傳給第一個(gè)參數(shù)
>>> class Student(object): def __init__(self,name): self.name = name def sayHello(lang): print(lang) if lang == ’en’: print(’Welcome!’) else: print(’你好!’) >>> Student.sayHello<function Student.sayHello at 0x02AC7810>>>> a = Student(’Bob’)>>> a.sayHello<bound method Student.sayHello of <__main__.Student object at 0x02AD03F0>>>>> Student.sayHello(’en’) # 類調(diào)用的時(shí)候,將’en’傳給了lang參數(shù)enWelcome!>>> a.sayHello() # 類實(shí)例對(duì)象調(diào)用的時(shí)候,將對(duì)象本身自動(dòng)傳給了lang參數(shù),不能再接收參數(shù)<__main__.Student object at 0x02AD03F0>你好! >>> a.sayHello(’en’) Traceback (most recent call last): File '<pyshell#7>', line 1, in <module> a.sayHello(’en’) TypeError: sayHello() takes 1 positional argument but 2 were given
2. staticmethod函數(shù)功能就是將一個(gè)方法定義成類的靜態(tài)方法,正確的方法是使用 @staticmethod裝飾器,這樣在實(shí)例對(duì)象調(diào)用的時(shí)候,不會(huì)把實(shí)例對(duì)象本身傳入靜態(tài)方法的第一個(gè)參數(shù)了。
# 使用裝飾器定義靜態(tài)方法>>> 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’) #類調(diào)用,’en’傳給了lang參數(shù)enWelcome!>>> b = Student(’Kim’) #類實(shí)例對(duì)象調(diào)用,不再將類實(shí)例對(duì)象傳入靜態(tài)方法>>> 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’) #類實(shí)例對(duì)象調(diào)用,’zh’傳給了lang參數(shù)zh你好!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. php模擬實(shí)現(xiàn)斗地主發(fā)牌2. 理解PHP5中static和const關(guān)鍵字3. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼4. Java如何基于反射機(jī)制獲取不同的類5. IntelliJ IDEA安裝插件的方法步驟6. Android table布局開(kāi)發(fā)實(shí)現(xiàn)簡(jiǎn)單計(jì)算器7. MyBatis中的JdbcType映射使用詳解8. Android 在 res/layout 文件夾 下創(chuàng)建一個(gè) 子文件夾實(shí)例9. Python random庫(kù)使用方法及異常處理方案10. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟

網(wǎng)公網(wǎng)安備