您的位置:首页 > 文旅 > 旅游 > 品牌建设10步通达_武汉推广工具_优秀营销软文100篇_关键词排名优化如何

品牌建设10步通达_武汉推广工具_优秀营销软文100篇_关键词排名优化如何

2025/7/17 1:53:33 来源:https://blog.csdn.net/qq_44815135/article/details/147232129  浏览:    关键词:品牌建设10步通达_武汉推广工具_优秀营销软文100篇_关键词排名优化如何
品牌建设10步通达_武汉推广工具_优秀营销软文100篇_关键词排名优化如何

Python 类方法示例

  类方法是绑定到类而不是实例的方法,它们使用 @classmethod 装饰器定义,第一个参数通常是 cls(表示类本身)。下面是一个具体的例子:

class Employee:"""员工类"""raise_amount = 1.04  # 类变量,表示加薪幅度def __init__(self, first, last, pay):"""初始化方法"""self.first = firstself.last = lastself.pay = payself.email = f"{first}.{last}@company.com"def apply_raise(self):"""加薪方法"""self.pay = int(self.pay * self.raise_amount)@classmethoddef set_raise_amount(cls, amount):"""类方法:设置所有员工的加薪幅度"""cls.raise_amount = amount@classmethoddef 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()),但推荐前者

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com