Python "private" name mangling and attribute instance vs class

I wrote a decorator who must access private variables and found this inconsistency. Can anyone explain this?

(Python 2.5)

Name management works as expected for attributes defined in the class:

>>> class Tester(object): ... __foo = "hi" >>> t = Tester() >>> t._Tester__foo 'hi' 

Instance attributes do not work (and so should we do it right?)

 >>> class Tester(object): ... def __init__(self): ... self.__foo = "hi" >>> t = Tester() >>> t._Tester__foo AttributeError: 'Tester' object has no attribute '_Tester__foo' 

PS Is the word "class attribute" correct? They are not static, but if you make one of them a list or some other mutable type, it will be split ...

Update

In fact, the second example works just fine. This was a hardware problem (rebooting helped).

+6
python private-members attributes name-mangling underscores
source share
1 answer

This is really wrong.

Name manipulation occurs during class creation; any functions related to malformed names are also adjusted.

I cannot reproduce your example, at least not in versions of Python 2.4, 2.5, 2.6, 3.1 and 3.2 on Mac:

 >>> class Tester(object): ... def __init__(self): ... self.__foo = "hi" ... >>> Tester()._Tester__foo 'hi' >>> Tester().__foo Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Tester' object has no attribute '__foo' 

If you break the function bytecode, you will see that the name is also garbled:

 >>> import dis >>> dis.dis(Tester.__init__) 3 0 LOAD_CONST 1 ('hi') 3 LOAD_FAST 0 (self) 6 STORE_ATTR 1 (_Tester__foo) 9 LOAD_CONST 0 (None) 12 RETURN_VALUE 

I checked the source of the compiler and all the names are launched through mangler, the path to the code that has remained unchanged since 2002 at least.

And yes, class attributes and instance attributes are the right conditions. Class attributes are always split, but assignment to an instance attribute is assigned to an instance. Mutating a list or other mutable objects does not match the attribute assignment.

+9
source share

All Articles