Python OOP:在更改 class 属性后自动更改 class 的实例?

Python OOP: Automatically changing instances of a class after changing a class attribute?

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

是否有可能改变 class 属性导致所有实例的薪水自动增加该值,而无需为每个实例明确地这样做?

听起来像是 properties 的绝佳用例。属性看起来像普通的实例变量,但作用却像方法。考虑

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

实际上,对 p1.salary 的每次访问都在调用对 real 字段 p1._salary 进行一些数学运算的方法,因此对 [=] 的任何更新13=]将在要求薪水时看到。