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


class Employee:
    pay_raise_percent = 0

    def __init__(self, name, salary): = 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?


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): = name
    self._salary = salary # "Private" variable

  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.

Answered By – Silvio Mayolo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published