having multiple Python interpreter levels active at the same time. Each level runs dif-
ferent code and operates independently.
Trace through this example’s output and code for more illumination. Here, we’re
moving on to the last quick example we have time and space to explore—in the name
of symmetry, using Python classes from C.
Using Python Classes in C
Earlier in this chapter, we learned how to use C++ classes in Python by wrapping them
with SWIG. But what about going the other way—using Python classes from other
languages? It turns out that this is really just a matter of applying interfaces already
shown.
Recall that Python scripts generate class instance objects by calling class objects as
though they were functions. To do this from C (or C++), simply follow the same steps:
import a class from a module, build an arguments tuple, and call it to generate an
instance using the same C API tools you use to call Python functions. Once you’ve got
an instance, you can fetch its attributes and methods with the same tools you use to
fetch globals out of a module. Callables and attributes work the same everywhere they
live.
To illustrate how this works in practice, Example 20-33 defines a simple Python class
in a module that we can utilize from C.
Example 20-33. PP4E\Integrate\Embed\Pyclasss\module.py
call this class from C to make objects
class klass:
def method(self, x, y):
return "brave %s %s" % (x, y) # run me from C
This is nearly as simple as it gets, but it’s enough to illustrate the basics. As usual, make
sure that this module is on your Python search path (e.g., in the current directory, or
one listed on your PYTHONPATH setting), or else the import call to access it from C will
fail, just as it would in a Python script. As you surely know if you’ve gotten this far in
this book, you can make always use of this Python class from a Python program as
follows:
...\PP4E\Integrate\Embed\Pyclass$ python
>>> import module # import the file
>>> object = module.klass() # make class instance
>>> result = object.method('sir', 'robin') # call class method
>>> print(result)
brave sir robin
Using Python Classes in C| 1535