strategy pattern and non-public virtual functions

pythoncurious at gmail.com pythoncurious at gmail.com
Mon Jun 5 10:07:45 EDT 2006


Hi python experts

In C++ I can do something like this:
class Base {
  public:
    void f() { this->f_(); }
  private:
    virtual void f_() = 0;
};

class Derived : public Base {
  private:
    void f_() { // Do something }
};

int main() {
    Derived d;
    d.f();
}

The point of this is that the a number of classes will inherit from
Base and only implement a private member function that only will be
accessed from the base class public 'f' function.
The Base::f() can then perform validation of input/return values, add
logging and things like that.
The users of the derived classes are unable to bypass this base class
function.

I've been wanting to do the same thing in python, to make sure that
there is no confusion about what function to call.

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()

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in f
AttributeError: 'D' object has no attribute '_B__f'

So my questions are:
1. Is there a "pythonic" way to do what I'm trying to do?
2. Should I be doing this at all? Any thoughts?




More information about the Python-list mailing list