+ 13

Variables in python

class Myclass: def __init__(self,n=1): self.__n=n def val_n(self): return (self.__n) obj=Myclass(2) obj.__n=3 print(obj.val_n()) What is the output? I'm confused between 2 and 3.

26th Oct 2019, 5:46 AM
Rishabh Gupta
Rishabh Gupta - avatar
2 ответов
+ 7
2. The syntax with two underscores within the class definition leads to name-mangling: The attribute __n will actually be named _Myclass__n and can be accessed as such. obj.__n = 3 writes into an instance dynamically, outside of the class definition, so it will create a new attribute that is named __n. The other attribute is still there, though, and val_n, being defined within the class, accesses that one.
26th Oct 2019, 8:02 AM
HonFu
HonFu - avatar
0
+
28th Oct 2019, 12:38 PM
Yevhen Morkovin
Yevhen Morkovin - avatar