Privacy and Inheritance

Mark Moales mmoales at fluent.com
Thu Sep 5 16:40:02 CEST 2002


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,
-------------- next part --------------
A non-text attachment was scrubbed...
Name: mmoales.vcf
Type: text/x-vcard
Size: 281 bytes
Desc: Card for Mark Moales
URL: <http://mail.python.org/pipermail/python-list/attachments/20020905/5cd59866/attachment.vcf>


More information about the Python-list mailing list