Python 类方法
Python 类方法示例
类方法是绑定到类而不是实例的方法,它们使用 @classmethod
装饰器定义,第一个参数通常是 cls
(表示类本身)。下面是一个具体的例子:
class Employee:
"""员工类"""
raise_amount = 1.04 # 类变量,表示加薪幅度
def __init__(self, first, last, pay):
"""初始化方法"""
self.first = first
self.last = last
self.pay = pay
self.email = f"{first}.{last}@company.com"
def apply_raise(self):
"""加薪方法"""
self.pay = int(self.pay * self.raise_amount)
@classmethod
def set_raise_amount(cls, amount):
"""类方法:设置所有员工的加薪幅度"""
cls.raise_amount = amount
@classmethod
def from_string(cls, emp_str):
"""类方法作为替代构造函数:从字符串创建员工对象"""
first, last, pay = emp_str.split('-')
return cls(first, last, int(pay))
def __repr__(self):
return f"Employee('{self.first}', '{self.last}', {self.pay})"
# 使用类方法设置加薪幅度
Employee.set_raise_amount(1.05) # 这会改变所有员工的加薪幅度
# 创建员工实例
emp1 = Employee('John', 'Doe', 50000)
emp2 = Employee('Jane', 'Smith', 60000)
print(emp1.raise_amount) # 输出: 1.05
print(emp2.raise_amount) # 输出: 1.05
# 使用类方法作为替代构造函数
emp_str = 'Mike-Johnson-75000'
emp3 = Employee.from_string(emp_str)
print(emp3) # 输出: Employee('Mike', 'Johnson', 75000)
关键点说明:
- 类方法定义:使用
@classmethod
装饰器,第一个参数是cls
(类本身) - 类方法用途:
- 修改类状态(如
set_raise_amount
) - 提供替代构造函数(如
from_string
)
- 修改类状态(如
- 调用方式:可以通过类直接调用(
Employee.set_raise_amount()
),也可以通过实例调用(emp1.set_raise_amount()
),但推荐前者
类方法常用于需要操作类变量或需要在不创建实例的情况下提供功能的场景。