strategy pattern and non-public virtual functions

"Martin v. Löwis" martin at v.loewis.de
Mon Jun 5 10:32:05 EDT 2006


pythoncurious at gmail.com wrote:
> Just translating this code to python won't work, due to the name
> mangling of private functions:
> class B(object):
>     def f(self):
>         self.__f()
> 
> class D(B):
>     def __f(self):
>         pass
> 
> d = D()
> d.f()
>
> So my questions are:
> 1. Is there a "pythonic" way to do what I'm trying to do?

Just use a single underscore, i.e. "_f" instead of "__f".


> 2. Should I be doing this at all? Any thoughts?

I can't spot the strategy pattern here; neither in the C++ code
nor in the Python code. For this to be the strategy pattern,
you should have two objects: the context, and the strategy
object. So for example, you could have

class Context:
  def f(self):
    return self.strategy.f()

class D:
  def f(self):
    pass

Then, assigning to context.strategy lets you change the
strategy dynamically.

It's not clear to what you are trying achieve with your
pattern, so it is hard to tell whether you should do this
at all. Most likely, the answer is "no".

If you are really looking for the strategy pattern:
be aware that people often use the strategy pattern
as a work-around for functions not being first-class
objects. In Python, they are, so you can often allow
for arbitrary callables in the strategy pattern.

Regards,
Martin



More information about the Python-list mailing list