Python中@staticmethod和@classmethod之间的区别
@classmethod裝飾器 (The @classmethod Decorator)
The @classmethod decorator is an inbuilt function decorator that gets evaluated after the function is defined. The result of the evaluation shadows the function definition. The @classmethod's first argument is always a class cls, similar to an instance method receiving self as its first argument.
@classmethod裝飾器是一個內置的函數裝飾器,在定義函數后會對其進行評估。 評估結果遮蓋了功能定義。 @classmethod的第一個參數始終是cls類,類似于將self作為其第一個參數的實例方法。
Syntax:
句法:
Class ABC(object):@classmethoddef function(cls, arg1, ...):...Exists to create class methods that are passed with the actual class object within the function call.
存在以創建在函數調用中與實際類對象一起傳遞的類方法。
Bound to the class and not to an instance.
綁定到類而不是實例。
Can modify the class state and that would be applied across all the instances.
可以修改類狀態,并將其應用于所有實例。
@staticmethod裝飾器 (The @staticmethod Decorator)
@staticmethods, similar to class methods, are methods that are bound to class rather than its object. However, they do not require a class instance creation. So, are not dependent on the state of the object.
與類方法類似, @staticmethods是綁定到類而不是對象的方法。 但是,它們不需要創建類實例。 因此,不依賴于對象的狀態。
Syntax:
句法:
Class ABC(object):@staticmethoddef function(arg1, arg2, ...):...Bound to the class and not to an instance
綁定到類而不是實例
Cannot modify the class state
無法修改類狀態
@classmethod和@staticmethod之間的比較 (Comparison between @classmethod and @staticmethod)
| Takes cls as first parameter | Needs no specific parameters |
| Can access or modify the class state | Cannot access the class state |
| They must have parameters | Knows nothing about the class state. Are similar to utility methods. |
| 以cls作為第一個參數 | 不需要特定參數 |
| 可以訪問或修改類狀態 | 無法訪問類狀態 |
| 他們必須有參數 | 對類狀態一無所知。 與實用程序方法相似。 |
@classmethod和@staticmethod的示例實現 (Example implementation of @classmethod and @staticmethod)
class City: def __init__(self, zip_code, name): self.zip_code = name self.name = name # a class method to create a city object. @classmethoddef city_name(cls, zip_code, name): return cls(zip_code, name) # a static method to check if a city is capital or not@staticmethoddef isCapital(city_name): if city_name == 'bengaluru':return Trueif __name__ == '__main__':bengaluru = City(560086, 'bengaluru')mysuru = City.city_name(560111, 'mysuru')print("city is {}".format(bengaluru.name))print("city is {}".format(mysuru.name))print("Bengaluru is capital :{}".format(City.isCapital('bengaluru')))Output
輸出量
city is bengaluru city is mysuru Bengaluru is capital : True翻譯自: https://www.includehelp.com/python/staticmethod-vs-classmethod.aspx
總結
以上是生活随笔為你收集整理的Python中@staticmethod和@classmethod之间的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法中的Strassen矩阵乘法
- 下一篇: 绝密543剧情介绍