差不多了,您只需要在内部进行一些自省
__getattr__,就可以在原始属性可调用时返回一个新的包装函数:
class Wrapper(object): def __init__(self,wrapped_class): self.wrapped_class = wrapped_class() def __getattr__(self,attr): orig_attr = self.wrapped_class.__getattribute__(attr) if callable(orig_attr): def hooked(*args, **kwargs): self.pre() result = orig_attr(*args, **kwargs) # prevent wrapped_class from becoming unwrapped if result == self.wrapped_class: return self self.post() return result return hooked else: return orig_attr def pre(self): print ">> pre" def post(self): print "<< post"
现在使用以下代码:
number = Wrapper(Simple)print "nCalling wrapped 'one':"number.one()print "nCalling wrapped 'two':"number.two("2")结果是:
Calling wrapped 'one':>> preone<< postCalling wrapped 'two':>> pretwo2<< post



