`SWIG/Examples/python/class/`

## Wrapping a simple C++ class

This example illustrates wrapping a simple C++ class to give a Python class.

## The C++ Code

Suppose you have some C++ classes described by the following (and admittedly lame) header file:

>     /* File : example.h */

>     class Shape {
>     public:
>       Shape() {
>         nshapes++;
>       }
>       virtual ~Shape() {
>         nshapes--;
>       }
>       double  x, y;
>       void    move(double dx, double dy);
>       virtual double area() = 0;
>       virtual double perimeter() = 0;
>       static  int nshapes;
>     };

>     class Circle : public Shape {
>     private:
>       double radius;
>     public:
>       Circle(double r) : radius(r) { }
>       virtual double area();
>       virtual double perimeter();
>     };

>     class Square : public Shape {
>     private:
>       double width;
>     public:
>       Square(double w) : width(w) { }
>       virtual double area();
>       virtual double perimeter();
>     };

## The SWIG interface

A simple SWIG interface for this can be built by simply grabbing the header file like this:

>     /* File : example.i */
>     %module example

>     %{
>     #include "example.h"
>     %}

>     /* Let's just grab the original header file here */
>     %include "example.h"

Note: when creating a C++ extension, you must run SWIG with the `-c++` option like this:

>     % swig -c++ -python example.i

## A sample Python script

Click here to see a script that calls the C++ functions from Python.

## Key points

- To create a new object, you call a constructor like this:

  >     c = example.new_Circle(10.0)

- Member variables of the C++ class are wrapped as attributes of the Python class. For example:

  >     c.x = 15   # Set member data
  >     x = c.x    # Get member data

- Member function are invoked as you would expect:

  >     print "The area is ", c.area()

- To invoke a destructor, simply call `del` on the object:

  >     del c    # Deletes a shape

- Static member variables are wrapped as C global variables. For example:

  >     n = example.cvar.Shape_nshapes     # Get a static data member
  >     example.cvar.Shapes_nshapes = 13   # Set a static data member

## General Comments

- SWIG does know how to properly perform upcasting of objects in an inheritance hierarchy (including multiple inheritance). Therefore it is perfectly safe to pass an object of a derived class to any function involving a base class.
- C++ Namespaces - %nspace isn't yet supported for Python.