Why a classmethod can change the value of a class variable for one instance but not for another instance?

Viewed 110

I have changed the value of class variable raise_amount for one instance. Later I have changed the value of the class variable with the classmethod set_raise_amt but it could not change the value for that particular instance, even though for the other instance it was changed. It's probably a noob question, but please help me understand.

class Employee:
    """
    A class that keeps employee records
    """
    raise_amount = 1.04

    def __init__(self, first, last):
        self.first = first
        self.last = last

    @classmethod
    def set_raise_amt(cls, amount):
        cls.raise_amount = amount


emp_1 = Employee("Test1", "Title1")
emp_2 = Employee("Test2", "Title2")

emp_1.raise_amount = 1.07
Employee.set_raise_amt(1.09)
Employee.raise_amount = 1.09

print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)

The output is

1.09
1.07
1.09
[Finished in 0.084s]
3 Answers

You did not "change it" for emp_1. You created the instance member. Therefore, when asking for emp_1.raise_amount, the instance member value is returned, whereas emp_2.raise_amount is the class member.

Use @staticmethod instead of @classmethod :

@staticmethod
def set_raise_amt(amount):
    Employee.raise_amount = amount
Related