@classmethod是 Python 中的一个装饰器,用于定义类方法。类方法是绑定到类而不是实例的方法,可以通过类或实例调用。

基本用法:

class MyClass:
	
	def __init__(self):
		self.x = 0
	
	@classmethod
	def my_class_method(cls):
		pass

	
MyClass.my_class_method()

obj = MyClass()
obj.my_class_method()

使用@classmethod装饰的方法有以下特点:

  • 第一个参数是cls(通俗约定,class 的缩写),指向类本身,而不是示例;
  • 可以通过类和示例调用,在这个例子中,既可以使用MyClass.my_class_method()调用,也可以使用obj.my_class_method()调用;
  • 不能访问实例的属性;

类方法在继承时会知道它是在哪个类中被调用:

class Parent:
	
    @classmethod
    def class_method(cls):
        print(f"Class method in {cls.__name__}")
		
		
class Child(Parent):
    pass

Parent.class_method()  # 输出: Class method in Parent
Child.class_method()   # 输出: Class method in Child

@classmethod 常用场景

1. 用于替代构造函数

class Integer:
	
    def __init__(self, value):
        self.value = value
    
    @classmethod
    def from_str(cls, str_value):
		
        if str_value == 'six':
            return cls(6) #等效于 return Integer(6)
		
        pass
	
        return Integer(0)
    
    def __str__(self):
        return str(self.value)

#标准构造方法
int1 = Integer(1)

# 使用类方法作为替代构造函数
int2 = Integer.from_str("six")

2. 访问和修改类的状态

class Counter:
	
    count = 0  # 类变量
    
    def __init__(self):
        Counter.count += 1
    
    @classmethod
    def get_count(cls):
        return cls.count

print(Counter.get_count())  # 0

for i in range(10):
	_ = Counter()

print(Counter.get_count())  # 10