pythonpython-3.xvariable-assignmentclass-variables

Set class variable using @classmethod


I have a class Employee with a class variable raise_amount. I created two instances, emp_1 & emp_2, for this class.

This question is not asking, what is a class variable, or how class variables differ from instance variables. This is about assignment of class variables.

I am trying to change the raise_amount variable of this class through the @classmethod method set_raise_amt(cls, amount).

If I set emp_1.raise_amount=3 first, then I called the emp_1.set_raise_amt(30).

I got:

emp_1.raise_amount=3

emp_2.raise_amount=30

Isn't the class method suppose to set both of raise_amount to 30?

class Employee:
    raise_amount=1.04

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

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

emp_1=Employee('Corey','Scott',50000)
emp_2=Employee('Test','UserA',60000)

emp_1.raise_amount=3
emp_1.set_raise_amt(30)

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

#the results will be:
# 3
# 30
# 30

Solution

  • You've added a new attribute for emp_1 with emp_1.raise_amount = 3.

    Try this and see the result:

    print(emp_1.__dict__)
    print(emp_2.__dict__)
    # will print:
    # {'first': 'Corey', 'last': 'Scott', 'pay': 50000, 'raise_amount': 3}
    # {'first': 'Test', 'last': 'UserA', 'pay': 60000}
    

    When print emp_1.raise_amount, the new instance attribute is printed. While for emp_2, the class attr/var is printed.