Deriving a Python Class

| Deriving a Python Class

Continuing, we can derive from our base class Base in Python and override the virtual function in Python. Before we can do that, we have to set up our `class_` wrapper as:

`

        class_<Base, BaseWrap, boost::noncopyable>("Base")
            ;

`

Otherwise, we have to suppress the Base class' `no_init` by adding an `__init__()` method to all our derived classes. `no_init` actually adds an `__init__` method that raises a Python RuntimeError exception.

`

        >>> class Derived(Base):
        ...     def f(self):
        ...         return 42
        ...

`

Cool eh? A Python class deriving from a C++ class!

Let's now make an instance of our Python class `Derived`:

`

        >>> derived = Derived()

`

Calling `derived.f()`:

`

        >>> derived.f()
        42

`

Will yield the expected result. Finally, calling calling the free function `call_f` with `derived` as argument:

`

        >>> call_f(derived)
        42

`

Will also yield the expected result.

Here's what's happening:

1. `call_f(derived)` is called in Python
2. This corresponds to `def("call_f", call_f);`. Boost.Python dispatches this call.
3. `int call_f(Base& b) { return b.f(); }` accepts the call.
4. The overridden virtual function `f` of `BaseWrap` is called.
5. `call_method<int>(self, "f");` dispatches the call back to Python.
6. `def f(self): return 42` is finally called.

Copyright © 2002-2003 David Abrahams
Copyright © 2002-2003 Joel de Guzman
Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.