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

Time:10-21

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

is it possible to make it so that changing a class attribute leads to an automatic increase in the salary of all instances by this value without doing that explicitly for each of them?

CodePudding user response:

Sounds like an excellent use case for properties. Properties look like ordinary instance variables but act like methods. Consider

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

In reality, every access to p1.salary is calling a method that does some math on the real field p1._salary, so any updates to Employee.pay_raise_percent will be seen whenever the salary is requested.

  • Related