我正在实例化一个 A 类(我从某人那里导入
否则,所以我无法修改它)到我的 X 类中。
有没有办法可以拦截或包装对 A 中方法的调用?
即,在下面的代码中我可以调用
x.a.p1()
并得到输出
X.pre
A.p1
X.post
很多TIA!
class A:
# in my real application, this is an imported class
# that I cannot modify
def p1(self): print 'A.p1'
class X:
def __init__(self):
self.a=A()
def pre(self): print 'X.pre'
def post(self): print 'X.post'
x=X()
x.a.p1()
这是我和我的同事提出的解决方案:
from types import MethodType
class PrePostCaller:
def __init__(self, other):
self.other = other
def pre(self): print 'pre'
def post(self): print 'post'
def __getattr__(self, name):
if hasattr(self.other, name):
func = getattr(self.other, name)
return lambda *args, **kwargs: self._wrap(func, args, kwargs)
raise AttributeError(name)
def _wrap(self, func, args, kwargs):
self.pre()
if type(func) == MethodType:
result = func( *args, **kwargs)
else:
result = func(self.other, *args, **kwargs)
self.post()
return result
#Examples of use
class Foo:
def stuff(self):
print 'stuff'
a = PrePostCaller(Foo())
a.stuff()
a = PrePostCaller([1,2,3])
print a.count()
Gives:
pre
stuff
post
pre
post
0
因此,在创建对象的实例时,请使用 PrePostCaller 对象包装它。之后,您可以继续使用该对象,就好像它是包装对象的实例一样。使用此解决方案,您可以在每个实例的基础上进行包装。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)