Python classmethod裝飾器原理及用法解析
英文文檔:
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’>子類的類對象調用父類的類方法
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. 將properties文件的配置設置為整個Web應用的全局變量實現方法2. SpringBoot集成SSM、Dubbo、Redis、JSP的案例小結及思路講解3. python爬蟲利用代理池更換IP的方法步驟4. JavaScript forEach中return失效問題解決方案5. JS算法題解旋轉數組方法示例6. PHP設計模式之迭代器模式Iterator實例分析【對象行為型】7. VMware如何進入BIOS方法8. python中pandas.read_csv()函數的深入講解9. Python語言規范之Pylint的詳細用法10. springboot用controller跳轉html頁面的實現
