|
Re: registering simple conversions from/to python: msg#00302python.c++
"Brett Calcott" <brett.calcott@xxxxxxxxxxxxxxx> writes: > "David Abrahams" <dave@xxxxxxxxxxxxxxxxxxxx> wrote >> >> > I'd like to pythonise my classes a little by allowing tuples to be >> > passed to and from the data values. >> > >> > In python in would look something like this: >> > >> > class C(object): >> > def __init__(self, x=0.0, y=0.0): >> > self.x = x >> > self.y = y >> > >> > def get_xy(self): >> > return self.x, self.y >> > >> > def set_xy(self, xy): >> > self.x, self.y = xy >> > >> > xy = property(get_xy, set_xy) >> > >> > >> > I guess I would start by created a pair<x, x> object, and then >> > register inward and outward conversions for it. >> > >> > Is there a simple recipe for registering these conversions? >> >> Brett, >> >> I'm sorry, I can't tell what you're trying to do. Could you please >> show an example of your C++ class and how you'd like to use it from >> Python? >> > Sorry, it was a little terse :) > > The point is that in the python class above I can do this: > > c = C() > c.x = 10.0 > c.y = 5.0 > > But, with the property added, I can do this too: > > c.xy = 10.0, 5.0 > > Which is kinda cool. I want to be able to do the same kind of thing from > C++. It is easy in boost_python to add a couple of data variables x and > y, but how to add the property wasn't obvious as I need to to be able to > unwrap and rewrap tuples/lists. > > I think Ralf has supplied enough information to get me started. Ralf's info is good, but it appears to have nothing to do with this problem. All you need is to use the add_property method with a function which takes a tuple: void set_xy(C& c, boost::python::tuple xy) { c.x = xy[0]; c.y = xy[1]; // should check that xy is only 2 elements long here } boost::python::tuple get_xy(C& c) { return boost::python::make_tuple(c.x, c.y); } class_<C>("C") .add_property("xy", get_xy, set_xy) ; -- Dave Abrahams Boost Consulting www.boost-consulting.com |
|
| <Prev in Thread] | Current Thread | [Next in Thread> |
|---|---|---|
| Previous by Date: | Re: [newbie] Question on embedding/extending with boost::python: 00302, Brett Calcott |
|---|---|
| Next by Date: | RE: Re: using BOOST_PYTHON_STATIC_LIB: 00302, Achim Domma \(ProCoders\) |
| Previous by Thread: | Re: registering simple conversions from/to pythoni: 00302, Brett Calcott |
| Next by Thread: | Re: registering simple conversions from/to python: 00302, Brett Calcott |
| Indexes: | [Date] [Thread] [Top] [All Lists] |
| News | FAQ | advertise |