Binding? problem

Scott David Daniels Scott.Daniels at Acm.Org
Mon Sep 13 20:46:31 CEST 2004


Josh English wrote:
> What I want to do is have a class method that takes methods from one 
> class and applies them to the class instance, overriding the 'self' in 
> the method from the Library class to the Runner class.

There _is_ an issue of methods knowing what class they were bound in.
However, if you are willing to use staticmethod:

     # Using curry (someday to show as functional.partial) as defined in:
     # <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549>
     import new

     def curry(*args, **okwargs):
         assert args
         if okwargs:
             def curried(*iargs, **ikwargs):
                 if ikwargs:
                     kwargs = okwargs.copy()
                     kwargs.update(ikwargs)
                 else:
                     kwargs = okwargs
	        return args[0](*(args[1:] + iargs), **kwargs)
             return curried

         assert len(args) >= 2
         if len(args) == 2:
             return new.instancemethod(args[0], args[1], object)

         if len(args) <= 1:
             return args[0]
         ## The following runs in the wrong order
         ## return new.function(args[0].func_code,
         ##                     args[0].func_globals, argdefs=args[1:])
         def scurried(*iargs, **kwargs):
             return args[0](*(args[1:] + iargs), **kwargs)
         return scurried

     class S(object):
         def __init__(self, value):
             self.value = value

         def __repr__(self):
             return '%s(%r)' % (self.__class__.__name__, self.value)

# Python 2.3 (and 2.2?) synax:
     class Library(object):
         # Cannot have "true" methods -- must be normal functions
         def do_this(self):
             self.s.value = 'this'
         do_this = staticmethod(do_this)

# Python 2.4 syntax:
#    class Library(object):
#        # Cannot have "true" methods -- must be normal functions
#        @staticmethod
#        def do_this(self):
#            self.s.value = 'this'

     class Runner(object):
         def __init__(self):
             self.s = S('whock')

         def imports(self, library):
              for name in dir(library):
                  if not name.startswith('_'):
                      value = getattr(library, name)
                      if callable(value):
                          setattr(self, name, curry(value, self))

         def __repr__(self):
             return '<%s %s>' % (self.__class__.__name__, self.s)


-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list