print(num.square())
num.data = 99
print(num.data)
num.display()
num.mul(2) # mul() is implemented in Python
num.display()
print(num) # repr from shadow superclass
del num
Now we get extra messages out of add calls, and mul changes the C++ class’s data
member automatically when it assigns self.data—the Python code extends the C++
code:
.../PP4E/Integrate/Extend/Swig/Shadow$ python main_subclass.py
Number: 1
in Python add...
add 4
Number=5
sub 2
Number=3
9
99
Number=99
in Python mul...
Number=198
<__main__.MyNumber; proxy of <Swig Object of type 'Number *' at 0x7ff4baa0> >
~Number: 198
In other words, SWIG makes it easy to use C++ class libraries as base classes in your
Python scripts. Among other things, this allows us to leverage existing C++ class li-
braries in Python scripts and optimize by coding parts of class hierarchies in C++ when
needed. We can do much the same with C extension types today since types are classes
(and vice versa), but wrapping C++ classes with SWIG is often much simpler.
Exploring the wrappers interactively
As usual, you can import the C++ class interactively to experiment with it some more—
besides demonstrating a few more salient properties here, this technique allows us to
test wrapped C++ classes at the Python interactive prompt:
.../PP4E/Integrate/Extend/Swig/Shadow$ python
>>> import _number
>>> _number.__file__ # the C++ class plus generated glue module
'_number.dll'
>>> import number # the generated Python shadow class module
>>> number.__file__
'number.py'
>>> x = number.Number(2) # make a C++ class instance in Python
Number: 2
>>> y = number.Number(4) # make another C++ object
Number: 4
1510 | Chapter 20: Python/C Integration