Private functions and inheritance

Neil Cerutti horpner at yahoo.com
Mon Jul 16 11:27:00 EDT 2007


On 2007-07-16, Maciej Blizi?ski <maciej.blizinski at gmail.com> wrote:
> Hello,
>
> I've come across something that I don't quite understand about
> Python's inheritance. Consider the following code snippet:
>
> class A(object):
>     def call_bar(self): return self.bar()
>     def call___bar(self): return self.__bar()
>     def __bar(self): return "A::__bar()"
>     def bar(self): return "A::bar()"

> class B(A):
>     def __bar(self): return "B::__bar()"
>     def bar(self): return "B::bar()"
>
> b = B()
> print "calling B::call_bar():", b.call_bar()
> print "calling B::call___bar():", b.call___bar()
>
> The result is:
>
> calling B::call_bar(): B::bar()
> calling B::call___bar(): A::__bar()

the __* naming convention for class private attributes is
intended to "help ensure" that attribute names of derived classes
cannot conflict with private attribute names in any base classes.
I.e., you should not use that naming convention when you *intend*
to override it in a derived class. If you do use the __* naming
convention, use it only for attributes that should not be
overrided or accessed by derived classes.

the weasel words from the documentation (which I put in quotes)
are there because the feature doesn't work (in all cases).

-- 
Neil Cerutti
The doctors X-rayed my head and found nothing. --Dizzy Dean



More information about the Python-list mailing list