Record the usage for your own query
reference
- @classmethod, @staticmethod, @property, class decorators
- Similarities and differences between staticmethod and classmethod decorators in python
@classmethod
In the object-oriented C++, there are static modified static methods, which can be accessed by the class or by the instantiated object. Similar to it in the python class is @classmethod, the class method.
example
Examples are as follows:
class Dog:
# 类属性
dogsum = {
}
def __init__(self, name, gender, age, type) -> None:
self.name = name
self.gender = gender
self._age = age
self.type = type
Dog.dogsum.setdefault(type, 0)
Dog.dogsum[type] += 1
@classmethod
def get_sum(cls, type):
return cls.dogsum[type]
dog = Dog("xiaohei", "male", 5, "tugou")
dog = Dog("xiaohong", "female", 6, "tugou")
dog = Dog("xiaohuang", "male", 7, "taidi")
print(Dog.dogsum)
print(Dog.get_sum("tugou"))
result:
{'tugou': 2, 'taidi': 1}
2
It can be seen that we define a class attribute dogsum in the class to count the number of dogs of different types, and modify the dogsum when creating the class. Because this attribute is a class attribute, a class method should be defined to access it, namely the get_sum method. After being @classmethod
modified, compared to the method of ordinary classes, he will not pass in parameters self
, but will pass in parameters cls
to represent this class. After that, the method can be called by the class, and it can also be called by any instantiated object.
Without using @classmethod
modifiers, try the following:
class Dog:
# 类属性
dogsum = {
}
def __init__(self, name, gender, age, type) -> None:
self.name = name
self.gender = gender
self._age = age
self.type = type
Dog.dogsum.setdefault(type, 0)
Dog.dogsum[type] += 1
def get_sum(self, type):
return Dog.dogsum[type]
dog0 = Dog("xiaohei", "male", 5, "tugou")
dog1 = Dog("xiaohong", "female", 6, "tugou")
dog2 = Dog("xiaohuang", "male", 7, "taidi")
print(Dog.dogsum)
print(dog0.get_sum("tugou"), dog1.get_sum("tugou"))
result:
{'tugou': 2, 'taidi': 1}
2 2
It can be seen that it can still be achieved, but it is not @classmethod
as standardized as using modification.
@staticmethod
For @classmethod
, it needs to pass in parameters cls
to represent this class, and for @staticmethod
, it does not need to pass in any parameters related to this class, so it is more like a method that has nothing to do with this class. It would be more systematic to put it into the relevant class at that time.