How does python handle a simultaneous reference to a variable via self and as a class attribute(static)? -


more importantly, if can explain output of 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 above code 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 refer supposed class attribute num, , add value using self. next line same variable being accessed class variable. reasonable assume variable being used both static , self variable. how can variable both static , self variable ? (or there missing here)

the num attribute starts class attribute this:

 self.num+=10 

can expanded self.num = self.num + 10 . what's happening is: first instance property called num, don't find it, class property called num, , use set instance property value. in moment have both instance , class property using same num name.

edit

the explanation above partially correct. first, num property searched iadd method , if fails find (which does, on account of num being of immutable type, try reassignation procedure above


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -