国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Python基于staticmethod裝飾器標示靜態(tài)方法

瀏覽:4日期:2022-07-08 08:49:33

英文文檔:

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.

標示方法為靜態(tài)方法的裝飾器

說明:

1. 類中普通的方法,實際上既可以被類直接調(diào)用也可以被類的實例對象調(diào)用,但是被實例對象調(diào)用的時候,要求方法至少有一個參數(shù),而且調(diào)用時會將實例對象本身傳給第一個參數(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)用的時候,將’en’傳給了lang參數(shù)enWelcome!>>> a.sayHello() # 類實例對象調(diào)用的時候,將對象本身自動傳給了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ù)功能就是將一個方法定義成類的靜態(tài)方法,正確的方法是使用 @staticmethod裝飾器,這樣在實例對象調(diào)用的時候,不會把實例對象本身傳入靜態(tài)方法的第一個參數(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’) #類實例對象調(diào)用,不再將類實例對象傳入靜態(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’) #類實例對象調(diào)用,’zh’傳給了lang參數(shù)zh你好!

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 阳江市| 临清市| 乌审旗| 芦山县| 洪雅县| 兴宁市| 盐亭县| 宁明县| 庄河市| 东兰县| 泊头市| 肇州县| 建瓯市| 梅州市| 塘沽区| 平度市| 丽江市| 太保市| 罗平县| 威海市| 林周县| 商丘市| 义马市| 阿拉善右旗| 柳林县| 宝清县| 建昌县| 白山市| 南平市| 交口县| 呼玛县| 砚山县| 三都| 白玉县| 九江市| 高碑店市| 华池县| 定安县| 聂荣县| 通渭县| 秭归县|