+ 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.
2 odpowiedzi
+ 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.
0
+