+ 2
Python - strictly private instance attributes
As per my (limited) Python knowledge, obj.__n = 3 can't modify instance attribute since it's strictly private. But, why doesn't this instruction raise any error or warning? 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())
2 ответов
+ 3
Right here -> obj.__n = 3
The name __n is mangled so you'll always get an attribute error.
Fix it like so:
obj._Myclass__n = 3