The example I can think of is that class methods are often used as a replacement for constructors (__init__).
Here is a simple example:
class Calculator:
def __init__(self, *numbers):
self.numbers = numbers
def sum(self):
return sum(self.numbers)
def avg(self):
return sum(self.numbers)/len(self.numbers)
if __name__ == '__main__':
c = Calculator(1,2,3,4,5)
print(c.sum())
print(c.avg())
This is a completely useless calculator class, but let’s not worry about it so much. The constructor of this class uses star expression to complete the function of receiving any number of positional arguments. Let’s consider a situation. If a user wants How to construct this class given a sequence (List or Tuple)?
We can easily use classmethod to implement constructor replacements. The key reason is that the first parameter of classmethod receives a class object. This allows us to process the arguments passed in by classmethod to become acceptable in standard constructors. Enter, reuse the class object to create the object and return.
If this matter is handed over to the instance method, there will be one more conversion method using type(self). Using staticmethod requires hard-coding the class name in the method, which is not so appropriate:
The example I can think of is that class methods are often used as a replacement for constructors (
__init__
).Here is a simple example:
This is a completely useless calculator class, but let’s not worry about it so much. The constructor of this class uses star expression to complete the function of receiving any number of positional arguments. Let’s consider a situation. If a user wants How to construct this class given a sequence (List or Tuple)?
In fact, just use star expression:
But classmethod is another option at this time:
We can easily use classmethod to implement constructor replacements. The key reason is that the first parameter of classmethod receives a class object. This allows us to process the arguments passed in by classmethod to become acceptable in standard constructors. Enter, reuse the class object to create the object and return.
If this matter is handed over to the instance method, there will be one more conversion method using
type(self)
. Using staticmethod requires hard-coding the class name in the method, which is not so appropriate:If you want to know more about instance method, classmethod and staticmethod, you can refer to:
Under what circumstances is Python’s staticmethod used
The definitive guide on how to use static, class or abstract methods in Python
Questions I answered: Python-QA
Wait a minute and write an example~
python3
类方法
和静态方法
皆可以访问类
的类变量
,但不能访问实例变量
。静态变量
,python里好像只能通过闭包
来实现静态变量
.