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)

关键点说明:

  1. 类方法定义:使用 @classmethod 装饰器,第一个参数是 cls(类本身)
  2. 类方法用途
    • 修改类状态(如 set_raise_amount
    • 提供替代构造函数(如 from_string
  3. 调用方式:可以通过类直接调用(Employee.set_raise_amount()),也可以通过实例调用(emp1.set_raise_amount()),但推荐前者

类方法常用于需要操作类变量或需要在不创建实例的情况下提供功能的场景。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值