PEP-0318

Dave Benjamin ramen at lackingtalent.com
Thu Aug 12 14:30:09 EDT 2004


In article <10hianhqvg1qc8d at news.supernews.com>, John Roth wrote:
> One additional use case for decorators: prototype object systems.
> I've been experimenting with Hans Nowak's system, and I am now
> quite looking forward to having a single decorator that will bind the
> function into an instance. For example:
> 
> @instancemethod(myinstance)
> def go(self, wordList):
>     ---stuff---
> 
> The result is that the function gets wrapped by new.instancemethod
> and bound into the instance that's bound to myinstance.

One possible implementation of such:

import new

def instancemethod(obj):
    def decorate(func):
        setattr(obj, func.func_name, new.instancemethod(func, obj))
        return func
    return decorate
                        
class Empty(object): pass
                        
o = Empty()
o.a = 5
o.b = 6
                        
@instancemethod(o)
def a_plus_b(self):
    return self.a + self.b                            

print o.a_plus_b()

-- 
  .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
         "talking about music is like dancing about architecture."



More information about the Python-list mailing list