创建包装器类以围绕现有函数调用pre和post函数吗?

创建包装器类以围绕现有函数调用pre和post函数吗?,第1张

创建包装器类以围绕现有函数调用pre和post函数吗?

差不多了,您只需要在内部进行一些自省

__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


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5647116.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存