[C++-sig] hijacking getattr/setattr
Václav Šmilauer
eudoxos at arcig.cz
Thu May 7 19:21:21 CEST 2009
Hello,
I have wrapper c++ classes that are exposed to python that wrap "real"
c++ classes with data. Wrapper classes have some attributes that .def'ed
and .add_property'd in the glue code. Wrapped classes have also
attributes that are registered by name (for serialization purposes) and
I can retrieve them.
To be able to get both wrapper attributes and attributes of the wrapped
class, I use getitem/setitem for the latter ones. That makes the python
code a bit ugly and difficult to read:
b=O.bodies[44]
b.geom['radius']=5 ## .geom returns wrapped class holding geometry
attributes, is .add_property'ed
b.phys['mass']=8 ## .phys returns wrapped class holding physical
attributes, is .add_property'ed
print b['id'] ## get an attribute that exists as such in the
wrapped class
I would like to unify both approaches so that if I say b.id, the pyBody
object (wrapping a shared_ptr<Body> object) will first look if the
attribute 'id' is within attributes of the wrapper class; return it if
it is, look in the wrapped object attributes if it is not; return the
wrapped object attribute of that name if it exists, otherwise throw.
(The same for b.geom.radius, b.phys.mass)
I simulated that with pure python code (attached), but it is not clear
to me how to put this in boost::python.
Can I get some pointers? I can overrider __getattr__ and __setattr__ of
the wrapper class, but I don't know how to simulate the default behavior
of getattr/setattr, once the key wasn't found in the wrapped class, for
example.
Thanks,
Vaclav
More information about the Cplusplus-sig
mailing list