擅长:python、mysql、java
<p>我刚刚注意到,在我最初的设计中,无法将args和kwargs传递给包装类,下面是更新后的答案,以便将输入传递给包装函数。。。</p>
<pre><code>class Wrapper(object):
def __init__(self,wrapped_class,*args,**kargs):
self.wrapped_class = wrapped_class(*args,**kargs)
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)
self.post()
return result
return hooked
else:
return orig_attr
def pre(self):
print ">> pre"
def post(self):
print "<< post"
</code></pre>