Privacy and Inheritance

Eric Brunel eric.brunel at pragmadev.com
Wed Sep 4 04:19:34 EDT 2002


Dennis B. wrote:

> Greetings;
> 
> 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.
> 
> Like the following doesn't even seem to work:
> 
> class StandardNormal:
> 
>     def letEventZScore(self, eventZScore):
>         self.__eventZScore = float(eventZScore)
> 
> class DerivativeNormal(StandardNormal):
> 
>     def getCentral(self):
>         if self.__eventZScore < 0:
> 
> Unless I change that last line to something like:
> 
>         if self._StandardNormal__eventZScore < 0:
> 
> Maybe just missing the point all together, but wondering if anyone'll
> point out anything a little more elegant and/or intuitive.

In languages that have actual "private", "protected" and "public" 
attributes, private attributes are not inherited. They are visible only in 
the class that define them, not outside it and not in its sub-classes. What 
you want is a protected attribute, that is visible in the defining class 
and in its sub-classes.

Unfortunately, Python doesn't know anything about protected attributes. 
AFAIK, there's no simple way to do what you want: in Python, attributes are 
either private or public; there's nothing in between...
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com



More information about the Python-list mailing list