Privacy and Inheritance

Emile van Sebille emile at fenx.com
Fri Sep 6 10:32:32 EDT 2002


"Mark Moales" <mmoales at fluent.com> wrote in message
news:3D776CC2.CA928E38 at fluent.com...
> 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:

Just watch out for coincidental reuse of __privateVar in subclasses:

class BaseClass:
    def __init__(self):
        self.publicVar = 'Foo'
        self._protectedVar = 'Bar'
        self.__privateVar = 'Spam'
    def showme(self):
        print self.__privateVar

class SubClass(BaseClass):
    def aMethod(self):
        print self.publicVar
        print self._protectedVar
        # Can't do this because it's private
        # print self.__privateVar
        self.__privateVar = 'Ham'

a = SubClass()
a.showme()

a.aMethod()
a.showme()


--

Emile van Sebille
emile at fenx.com

---------







More information about the Python-list mailing list