类方法(Class Method)
一句话解释
@classmethod 接收 cls(类)而非 self——适合替代构造函数和工厂方法。
用大白话说
@classmethod 接收类本身(cls)作为第一个参数,而非实例(self)。这让它可以:1. 创建替代构造函数——最常见的用例(工厂方法)
- 访问/修改类级状态——跨实例共享的类变量
- 与继承配合——
cls是实际子类,所以类方法被正确继承经典模式是from_string()、from_dict()等——构造实例的替代方式。在子类上调用时,cls是子类,实现多态构造。
示例
python
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, date_str):
# Alternative constructor: "2024-01-15"
year, month, day = map(int, date_str.split("-"))
return cls(year, month, day)
@classmethod
def today(cls):
import datetime
t = datetime.date.today()
return cls(t.year, t.month, t.day)
d = Date.from_string("2024-01-15")
print(d.year, d.month, d.day) # 2024 1 15
t = Date.today()
print(t.year)@classmethod 接收 cls(类),实现替代构造函数(工厂方法)。cls() 多态地创建实例。
常见混淆
容易混淆的对象: 静态方法
关键区别: @classmethod 接收 cls(类)作为第一个参数——它可以创建实例和访问类状态。@staticmethod 不接收隐式参数——它是无法访问类或实例状态的普通函数。构造函数用 classmethod,工具函数用 staticmethod。
相关术语
相关资源
相关课程
- Python 面向对象
类方法。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。