Privacy and Inheritance

Dennis B. dcswest at flashmail.com
Thu Sep 5 21:20:18 EDT 2002


Hello Mark;

And thank you for that clarification!  Wasn't even aware of a convention
as such and it certainly answers my question!!!

Leads me to wonder why we wouldn't enforce this in Python too with the
interpreter and without workarounds, rather than strictly by having well
behaved programmers, but it does seem good how much Python encourages
behavior as such...

Thank you again,


On Thu, 2002-09-05 at 07:40, Mark Moales wrote:
> Dennis,
> 
> I think the point of the double underscores is to create "private"
> attributes similar to C++'s or Java's private keyword.  In other words,
> only the class that defines the attribute can access it.  Subclasses and
> others can't.  We use a single underscore here to denote "protected"
> attributes, or attributes that are accessible by subclasses.  However,
> the only way to enforce this in Python is by having well behaved
> programmers ;-)  Here's an example:
> 
> class BaseClass:
>     def __init__(self):
>         self.publicVar = 'Foo'
>         self._protectedVar = 'Bar'
>         self.__privateVar = 'Spam'
> 
> class SubClass(BaseClass):
>     def aMethod(self):
>         print self.publicVar
>         print self._protectedVar
>         # Can't do this because it's private
>         # print self.__privateVar
> 
> Mark
> 
> "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.
> > 
> > Thank you and have a great day,






More information about the Python-list mailing list