[python] nested attributes, style question
Hi, let's say we've got the following C++ classes: class position { public: float get_height() const; void set_height(float value); private: float height_; }; class object { public: position get_position() const; void set_position(const position& value); private: position pos_; }; This design is not fixed, but right now this is the starting point. When I added the boost.python interface to it using add_property(), I quickly noticed that using these classes feels somehow unpythonic: I cannot modify the height of the position of an object using obj.pos.height = x because get_position() returns the position by value, so the following set_height modifies a temporary instance of position. The work-around on the python side looks clumsy: position pos = obj.pos pos.height = x obj.pos = pos Now I wonder whether I just just go for public member variables on the C++ side and expose these using def_readwrite(). But this would couple the implementation to the interface. Moving the object class to another kind of position handling would be easy with the get/set-based interface using on-the-fly conversions, but nearly impossible with the public member. That's why I think of some kind of attribute proxy object that hides the C++ get/set stuff in a way that allows attribute manipulation on the python side but keeps interface and implementation separated on the C++ side. I'm not sure how this proxy would look like, but the idea feels somehow right... Is there a common solution to this problem? Does my proxy approach seem reasonable? Malte
Malte Clasen
Hi,
let's say we've got the following C++ classes:
class position { public: float get_height() const; void set_height(float value); private: float height_; };
class object { public: position get_position() const; void set_position(const position& value); private: position pos_; };
This design is not fixed, but right now this is the starting point. When I added the boost.python interface to it using add_property(), I quickly noticed that using these classes feels somehow unpythonic: I cannot modify the height of the position of an object using
obj.pos.height = x
because get_position() returns the position by value, so the following set_height modifies a temporary instance of position. The work-around on the python side looks clumsy:
Is there a common solution to this problem? Does my proxy approach seem reasonable?
http://thread.gmane.org/gmane.comp.python.c++/8966 should help. Use return_internal_reference. -- Dave Abrahams Boost Consulting www.boost-consulting.com
participants (2)
-
David Abrahams
-
Malte Clasen