Here is a stripped-down version of a Python Cookbook recipe. Is there a
simpler, more Pythonical, natural way of doing this?
------
#! /usr/bin/env python
# Modified from Python Cookbook entry 91192, "eiffelmeth od" by Andres
# Tuells. The url is
# http://aspn.activestate.com/ASPN/Coo...n/Recipe/91192
class MethodWraper(ob ject):
def __init__(self, method):
self.method = method
def __get__(self, inst, type=None):
result = wrapper(inst, self.method)
setattr(inst, self.method.__n ame__, result)
return result
class wrapper:
def __init__(self, inst, method):
self.instance = inst
self.method = method
def __call__(self, *args, **kargs):
print 'pre'
result = apply(self.meth od, (self.instance, ) + args, kargs)
print 'post'
return result
def test():
class C:
def f(self, arg):
print 'in f'
return arg+1
f = MethodWraper(f)
c = C()
print c.f(1)
if __name__=='__ma in__':
test()
------
simpler, more Pythonical, natural way of doing this?
------
#! /usr/bin/env python
# Modified from Python Cookbook entry 91192, "eiffelmeth od" by Andres
# Tuells. The url is
# http://aspn.activestate.com/ASPN/Coo...n/Recipe/91192
class MethodWraper(ob ject):
def __init__(self, method):
self.method = method
def __get__(self, inst, type=None):
result = wrapper(inst, self.method)
setattr(inst, self.method.__n ame__, result)
return result
class wrapper:
def __init__(self, inst, method):
self.instance = inst
self.method = method
def __call__(self, *args, **kargs):
print 'pre'
result = apply(self.meth od, (self.instance, ) + args, kargs)
print 'post'
return result
def test():
class C:
def f(self, arg):
print 'in f'
return arg+1
f = MethodWraper(f)
c = C()
print c.f(1)
if __name__=='__ma in__':
test()
------
Comment