How to access private variables in child classes?
The correct answer is: you should NOT access the private ( __
) attributes of other classes.
If you think that in your case it is absolutely necessary to refer to such attributes, then you should change the corresponding parent classes to provide explicit, documented access.
Also, programmers who come from languages with a specific OOP model (C ++, Java), which places great emphasis on the visibility of attributes (private, protected, public), can be abused by __
in Python. Perhaps __
were redundant from the start.
Finally, the worst solution is to find out the name distortion scheme that your version of Python uses and manually create the appropriate names for access:
>>> class C: ... def __init__(self): ... self.__x = 'x' ... >>> c = C() >>> c.__x Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'C' object has no attribute '__x' >>> import dis >>> dis.dis(C.__init__) 3 0 LOAD_CONST 1 ('x') 3 LOAD_FAST 0 (self) 6 STORE_ATTR 0 (_C__x) 9 LOAD_CONST 0 (None) 12 RETURN_VALUE >>> c._C__x 'x'
Studying the _Py_Mangle()
source code found an interesting feature: the initial underscore characters are removed from the class name, that is, the _C__x
name remains the same for the C
, _C
, __C
, etc. classes.
self._Animal__type
Details here: stackoverflow.com/questions/20261517/… - zed