Private functions and inheritance
Diez B. Roggisch
deets at nospam.web.de
Mon Jul 16 10:54:48 EDT 2007
Maciej Bliziński 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()
>
> In the latter case, it calls the base class' implementation. It
> probably goes along with Python's spec, but I found it surprising. I
> don't want to expose the __bar() function outside, but on the other
> hand i want to defer its implementation to a subclass. It seems like I
> need to make it public, doesn't it?
Yep. Just use a single underscore, and that's it. The reason why this
doesn't work as expected is that the name-mangling introduced by the
leading double underscores is purely a lexical scope based mechanism.
Diez
More information about the Python-list
mailing list