Python 中 @staticmethod 与 @classmethod 有什么区别?
@staticmethod 不接收任何隐式首参,只是挂在类上的普通函数;@classmethod 接收 cls 首参,能访问类属性、用于替代构造器。本文用示例讲清两者区别与适用场景。
区别在隐式参数:@staticmethod 什么都不传——只是个住在类命名空间里的普通函数;@classmethod 自动传入类本身 cls,因此能读写类属性、做"替代构造器"。
代码对比
class Date:
def __init__(self, year, month):
self.year, self.month = year, month
@staticmethod
def is_valid(year, month): # 无 self/cls
return 1900 <= year and 1 <= month <= 12
@classmethod
def from_string(cls, s): # 传 cls
y, m = s.split('-')
return cls(int(y), int(m)) # 替代构造器
Date.is_valid(2024, 6) # 直接用
Date.from_string('2024-06') # 返回实例
怎么选
- 逻辑上和类相关、但不需要访问类/实例状态 →
@staticmethod(工具函数); - 需要用到类本身(构造实例、读类属性、支持继承多态)→
@classmethod。
常见问题(FAQ)
Q:实例能调用 staticmethod 吗? 能,但不推荐——语义上属于类。
Q:classmethod 在继承中的好处? cls 会指向实际子类,from_string 在子类调用时返回子类实例。