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

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

Python classmethod裝飾器原理及用法解析

瀏覽:21日期:2022-07-08 08:46:07

英文文檔:

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:@classmethoddef 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’>子類的類對象調用父類的類方法

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

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 简阳市| 鄂托克前旗| 务川| 内江市| 申扎县| 天气| 察雅县| 永胜县| 宁安市| 炉霍县| 康平县| 全椒县| 湘西| 鄂温| 嘉义市| 赞皇县| 搜索| 绥江县| 天峨县| 太保市| 大连市| 清流县| 三河市| 翁源县| 洪湖市| 肥西县| 滕州市| 辰溪县| 阿城市| 广德县| 黄石市| 论坛| 广安市| 永登县| 罗江县| 江西省| 桓台县| 安康市| 文山县| 共和县| 贵德县|