av一区二区在线观看_亚洲男人的天堂网站_日韩亚洲视频_在线成人免费_欧美日韩精品免费观看视频_久草视

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

Python基于staticmethod裝飾器標示靜態方法

瀏覽: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.

標示方法為靜態方法的裝飾器

說明:

1. 類中普通的方法,實際上既可以被類直接調用也可以被類的實例對象調用,但是被實例對象調用的時候,要求方法至少有一個參數,而且調用時會將實例對象本身傳給第一個參數

>>> 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’) # 類調用的時候,將’en’傳給了lang參數enWelcome!>>> a.sayHello() # 類實例對象調用的時候,將對象本身自動傳給了lang參數,不能再接收參數<__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函數功能就是將一個方法定義成類的靜態方法,正確的方法是使用 @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你好!

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

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 亚洲在线| 99久久久国产精品 | 中文视频在线 | 日韩综合网 | 亚洲一区网站 | 亚洲精品中文字幕在线观看 | 久久精品国产一区 | 欧美精品1区 | 欧美一级α片 | 国产精品欧美一区二区 | www四虎影视 | 国产成人免费视频网站高清观看视频 | 精品久久久久久亚洲精品 | 午夜精品久久久久久久久久久久久 | 欧美手机在线 | 亚洲欧美综合精品久久成人 | 精品欧美乱码久久久久久1区2区 | 国产在线精品一区二区三区 | 一区二区成人 | 性国产xxxx乳高跟 | 精品一区二区在线观看 | 国产免费一区 | 男人天堂久久久 | av黄色片 | 999热视频| 97超碰人人草 | 中文字幕第90页 | 精品综合 | 日韩av在线一区 | 国产精品呻吟久久av凹凸 | 殴美一级片 | 久久久久久免费毛片精品 | 国产精品久久久久久久久婷婷 | 亚洲福利网| 国产精品一区二区三区在线播放 | 亚洲视频在线看 | 天堂亚洲网| 国产精品一区在线 | 亚洲欧美综合精品久久成人 | 亚洲第一天堂 | 视频二区在线观看 |