...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
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:
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.