strategy pattern and non-public virtual functions

Duncan Booth duncan.booth at invalid.invalid
Mon Jun 5 16:27:04 CEST 2006


> The users of the derived classes are unable to bypass this base class
> function.

Just to be clear, the users of the derived C++ classes *are* able to bypass 
the base class function and call f_() directly, they just have to be 
prepared to twist the rules somewhat. I know: I've been in the situation 
where there was absolutely no other way to get the job done other than to 
call a private method in a class supplied in a library which I couldn't 

To do the same in Python you simply make a rule 'dont call f_ directly' and 
you get effectively the same thing: users can call f_ if they really want, 
but they are breaking the rules if they do. The difference in Python is 
that you don't have to go to such extremes to break the rules.

The Pythonic way to do it:

class B(object):
    def f(self):

class D(B):
    def _f(self):

d = D()

Calling a method with a single leading underscore from outside the 
implementation of the class is generally accepted in Python to be 'breaking 
the rules' and therefore something only to be done by consenting adults in 
the full knowledge of the consquences of their actions.

More information about the Python-list mailing list