[C++-sig] Need strategic advice designing Boost/Python program
Ralf W. Grosse-Kunstleve
rwgk at yahoo.com
Mon Apr 30 23:45:10 CEST 2007
> This, together with your point further down that you want to add python
> methods that are only ever used inside python make it sound as if
> a C++ base class derived from in python may be the best approach.
FWIW: there is a very powerful alternative to this: injecting.
For example:
class _histogram(boost.python.injector, ext.histogram):
def show(self, f=None, prefix="", format_cutoffs="%.8g"):
if (f is None): f = sys.stdout
fmt = "%s" + format_cutoffs + " - " + format_cutoffs + ": %d"
for info in self.slot_infos():
print >> f, fmt % (prefix, info.low_cutoff, info.high_cutoff, info.n)
The boost.python.injector is a small utility class defined
in boost_adaptbx (adaptor toolbox), boost/python.py.
The difference is that objects of ext.histogram will have the
.show() method, even if they are created in C++.
I.e. even if you only have a C++ constructor, you can have pure
Python methods.
To give proper credit: this trick is due to David Abrahams. It was
one of the big aha moments in my life when he explained it to me.
Ralf
P.S.: you can also do it like this:
def histogram_show(self, f=None, prefix="", format_cutoffs="%.8g"):
# exact same code
ext.histogram.show = histogram_show
but it doesn't look nearly as nice. You can also make it look nice with
decorators if you don't care about Python 2.2 and 2.3 compatibility.
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20070430/1cda7daf/attachment-0001.htm>
More information about the Cplusplus-sig
mailing list