Using Classes and Objects in Python
This sidebar is meant to show how C++ objects appear when accessed from Python. Suppose the following declarations were wrapped into a module called Example:
#define OPTION1 10 #define OPTION2 20 extern int Value1 = 1234; extern int ProcessOptions ( int o1, int o2 ); extern char* OptionString ( int o ); class Option { public: int option; double d; char* name; Option () { option = 1; d = 3.1415; name = '/0'; }; double Compute ( int cycles ) { return d * cycles; }; };
In Python, we would first import the new module, then use the constants:
>>> import Example >>> Example.OPTION1 10 >>> Example.OPTION2 20 >>> Example.ProcessOptions ( Example.OPTION1, Example.OPTION2 ) 30 >>> Example.OptionString ( OPTION2 ) 'OPTION1' >>> o = Example.Option() >>> print o <C Option instance> >>> o.option 1 >>> o.name >>> o.name = "Best Option" >>> o.name 'Best Option' >>> o.Compute ( 20 ) 62.83 >>> o.d = 20.25 >>> o.Compute ( 15 ) 303.75
Python syntax is similar to C++, and the example above should be easy to follow. The "import Example" command at the Python prompt ">>>" loads the module created. The module defines its own namespace, Example, and each of the elements of the wrapped declarations is accessible through this namespace. An instance of the Option class is easily created with members and methods accessed in an intuitive manner. Because all the members of Option were declared public, the Python interface allows them to be used just as they would be used in C++.
More information about Python can be found at www.python.org.