[PyQt] SIP: C++/Python inheritance & casting issues.

Phil Thompson phil at riverbankcomputing.com
Thu May 29 10:21:02 BST 2014


On 29/05/2014 9:29 am, Christoff Kok wrote:
> Hi,
> 
> I have the following isse with C++/Python inheritance:
> e.g.
> base class: class Vehicle { }
> derived classes: motorcycle, car { int wheelCount = 4 }, truck, plane,
> train, etc.
> class VehicleStore {
>    vector<Vehicle> vehicleList;
> }
> 
> In my python interface, I want to access VehicleStore.vehicleList[0]
> (Or get a list of all the Car Vehicles)
> 
> In C++ I can access the derived class functions as follows:
> Vehicle* v = &vehicleStore.vehicleList[0];
> Car* c = dynamic_cast<Car*>(v);
> if(c == null) return; // the vehicle is not a car.
> // the vehicles' Car specific properties and methods can now be
> accessed.
> result = c.wheelCount; // result = 4;
> 
> In the SIP generated Python code VehicleStore.vehicleList is a python
> list containing python objects of type vehicle. When accessing a
> vehicle directly form the list, I get a python object of type vehicle
> back, not the derived type. The derived type specific members cannot
> be accessed, only the base (super) class' can. This makes sense,
> python was never told that the object is a derived type, only of type
> Vehicle.
> E.g.
> s = vehicleStore()
> s.vehcileList = {car(), plane(), truck(), motorcycle()}
> .
> .
> .
> car = s.vehcileList[0];
> 
> print(car.wheelCount) # Error the attribute wheelCount does not exist
> in type Vehicle.
> 
> I however want to access the derived type in Python. The only way I
> see this to be possible is to instruct VehicleStore's .sip code's
> vehicleList's %AccessCode to return the vehicleList python object
> containing types pointing to the correct derived type, instead of just
> to the super type.
> This is tricky as I will need to make use of some reflection. (I can't
> hardcode checks for the types of vehivles it, as a library may be
> plugged in specifying new types of vehicles, unbeknownst to me).
> 
> Is there perhaps an simpler and easier solution, perhaps SIP is
> already addressing this and I am unaware of it. Is there perhaps code
> generated by SIP that may help me find all the classes derived from a
> super(base) class?

You need to implement %ConvertToSubClassCode.

Phil


More information about the PyQt mailing list