[C++-sig] Idea: Injecting methods using Python 2.4 decorator syntax

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Sun Feb 20 14:47:48 CET 2005


With reference to my previous posting

  http://mail.python.org/pipermail/c++-sig/2005-February/008585.html

and this section in the Boost.Pyton documentation

 
http://www.boost.org/libs/python/doc/tutorial/doc/html/python/techniques.html#python.extending_wrapped_objects_in_python

Here is a neat alternative based on Python 2.4 decorators:

    # general purpose helper for injecting attributes
    class injector:

      def __init__(self, obj, attr):
        self.obj = obj
        self.attr = attr

      def __call__(self, attr_obj):
        setattr(self.obj, self.attr, attr_obj)

    class point:
    
      def __init__(self, (x,y)):
        self.xy = (x,y)

    @injector(point, "__str__")
    def attr_obj(self):
      return str(self.xy)

    p = point((1,2))
    print p

I am not sure about all the pros and cons compared to the
BoostPythonMetaclass approach shown in the Boost.Python documentation,
but at least I find it easier to understand and the injector is
completely independent of Boost.Python.

Cheers,
        Ralf



		
__________________________________ 
Do you Yahoo!? 
The all-new My Yahoo! - What will yours do?
http://my.yahoo.com 



More information about the Cplusplus-sig mailing list