class Employee:
pay_raise_percent = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
p1 = Employee('John', 50_000)
p2 = Employee('Alex', 75_000)
p3 = Employee('Caleb', 90_000)
Employee.pay_raise_percent = 1.04
print(p1.salary, p2.salary, p3.salary, sep='\n')
# 52000 78000 93600
Run Code Online (Sandbox Code Playgroud)
是否有可能使更改类属性导致所有实例的工资自动增加该值,而无需为每个实例显式执行此操作?
听起来是一个很好的属性用例。属性看起来像普通的实例变量,但行为却像方法。考虑
class Employee:
pay_raise_percent = 1.00
def __init__(self, name, salary):
self.name = name
self._salary = salary # "Private" variable
@property
def salary(self):
return self._salary * Employee.pay_raise_percent
p1 = Employee('John', 50_000)
print(p1.salary) # 50000
Employee.pay_raise_percent = 1.04
print(p1.salary) # 52000
Run Code Online (Sandbox Code Playgroud)
实际上,每次访问都会调用一个在真实字段p1.salary上进行一些数学运算的方法,因此每当请求薪水时都会看到对的任何更新。p1._salaryEmployee.pay_raise_percent