Reputation: 97
More importantly, if someone can explain the output of the following code.
class myclass:
num = 10
def mymethod(self):
print("PrevValue of self.num->",self.num)
print("Prev Value of myclass.num->",myclass.num)
self.num+=10
myclass.num+=20
print("PostValue of self.num->",self.num)
print("PostValue of myclass.num->",myclass.num)
obj1 = myclass()
obj2 = myclass()
obj2.mymethod()
obj1.mymethod()
The output of the above code is as follows.
('PrevValue of self.num->', 10)
('Prev Value of myclass.num->', 10)
('PostValue of self.num->', 20)
('PostValue of myclass.num->', 30)
('PrevValue of self.num->', 30)
('Prev Value of myclass.num->', 30)
('PostValue of self.num->', 40)
('PostValue of myclass.num->', 50)
The line 7, i.e self.num+=10 seems to refer the supposed class attribute num, and add a value to that using self. The next line the same variable is being accessed as a class variable. So it is reasonable to assume that the variable is being used both as a static and a self variable. How can a variable be both static and a self variable ? (Or there is something that I could be missing here)
Upvotes: 2
Views: 57
Reputation: 4770
The num
attribute starts as a class attribute but then this:
self.num+=10
can be expanded to self.num = self.num + 10
. What's happening is: First we look for a instance property called num, we don't find it, then we look for a class property called num, and we use that to set the instance property value. In this moment you have both a instance and a class property using the same num
name.
EDIT
The explanation above is only partially correct. First, the num
property is searched for a iadd method and if it fails to find that (which it does, on account of num being of an immutable type, it will try to do the reassignation procedure above
Upvotes: 3