0

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

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 set_raise_amt(30). I got :

emp_1.raise_amount=3

emp_2.raise_amount=30

I don't understand. 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
halfelf
  • 9,737
  • 13
  • 54
  • 63

1 Answers1

0

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.

halfelf
  • 9,737
  • 13
  • 54
  • 63