+ 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())

4th Apr 2020, 8:13 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
2 Answers
+ 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
4th Apr 2020, 9:23 AM
Mensch
Mensch - avatar