I wrote a simple program.
class Sample:
num =45
def __init__(self):
print('Inside constructor')
@classmethod
def modifyUsingClassMethod(cls):
cls.num = cls.num + 45
@staticmethod
def modifyUsingStaticMethod():
Sample.num = Sample.num+5
s1 = Sample()
s2 = Sample()
s1.modifyUsingClassMethod()
print(s1.num, s2.num)
s1.num = s1.num + 5
print(s1.num)
s1.modifyUsingClassMethod()
print(s1.num, s2.num)
s1.modifyUsingStaticMethod()
print(s1.num, s2.num)
Output:
Inside constructor
Inside constructor
90 90
95
95 135
95 140
Can anyone explain how and why the @staticmethod and @classmethod are acting on the variable 'num'?. Why does the output shows 95,135 even after I changed the value of num using s1 instance using modifyUsingClassMethod() and why not it is updating in both cases using @staticmethod and @classmethod?
I guess when I am referring to the variable num using class object then python is treating the variable num as an instance variable but when I change the variable num using Class name then the value is not updating in the s1 but in s2. I am highly confused how @classmethod and @staticmethod works.