Privacy and Inheritance

Erik Max Francis max at alcyone.com
Wed Sep 4 06:40:10 CEST 2002


"Dennis B." wrote:

> Have enough confidence in Python to realize this is probably just my
> misunderstanding, but wondering why Python mangles private, double
> underscore attributes with the name of the base class even if they're
> inherited and the instance is that of the sub class.

Double underscore mangling is done with the name of the class involved,
so it is in effect a private variable to that class only; subclasses
will not have access to it (without doing the unmangling yourself,
obviously, as you've seen).

The use of double underscores to mangle names should be viewed as
something specific to that class which nothing else will ever use; in
terms of access restriction it's similar to the private keyword in C++.

What you want is something local to that class and its subclasses, which
would correspond to C++ protected access.  There's no mangling mechanism
to do this, although a common convention (and one I use when I'm really
concerned about access restriction in Python, which is fairly rare) is
to use a single underscore.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ There is nothing so subject to the inconstancy of fortune as war.
\__/ Miguel de Cervantes
    Church / http://www.alcyone.com/pyos/church/
 A lambda calculus explorer in Python.



More information about the Python-list mailing list