【发布时间】:2019-01-13 13:55:49
【问题描述】:
我观看了一个解释 @classmethods、实例方法和 @staticmethods 的 youtube 视频。我了解如何使用它们。我只是不明白何时使用它们以及为什么使用它们。这是他在 youtube 视频中为我们提供的 @classmethods 代码。
class Employee:
# class object attributes
num_of_emps = 0
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
Employee.num_of_emps += 1
def fullname(self):
return f'{self.first} {self.last}'
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
@classmethod
def set_raise_amt(cls, amount):
cls.raise_amt = amount
@classmethod
def from_string(cls, emp_str):
first, last, pay = emp_str.split('-')
return cls(first, last, pay)
emp_1 = Employee('Corey', 'Shaffer', 50000)
emp_2 = Employee('Test', 'Employee', 60000)
emp_3 = Employee.from_string('Ezekiel-Wootton-60000')
print(emp_3.email)
print(emp_3.pay)
为什么我对 from_string 方法使用@classmethod?我认为使用没有装饰器的普通实例方法更有意义,因为我们没有引用类。正确的?!?我们指的是每个将字符串作为参数传递的实例。
【问题讨论】:
-
这个想法是
set_raise_amt更改所有 员工的数量,而不是这个特定的员工。而from_string在命令行中获取它需要的所有信息,因此它不需要实例。 -
感谢这个例子。
标签: python class-method