Why does the val_n function return an older value of self.__n? Seems to me that if obj.__n has been updated to 3, calling self.val__n should return 3 and not 2.
class myClass: def __init__(self,n=1): self.__n=n def val_n(self): return self.__n #create an instance, __n is 2 obj=myClass(2) #update __n to 3 obj.__n=3 #verify obj.__n has changed from 2 to 3 print(obj.__n) #why does this still return 2? print(obj.val_n())
obj.__n = 3seems to change the value. The answer is that this assignment, as it does not occur inside a method definition, creates a new attribute whose name really is__n, as opposed to_myClass__n. Usedir(obj)to show that attributes by both names exist after the assignment.