python调post_Python:用pre和post方法包装方法调用

以下是我和同事们想出的解决方案: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()

给出:pre

stuff

post

pre

post

0

因此,在创建对象的实例时,用PrePostCaller对象包装它。之后,您将继续使用该对象,就像它是包装对象的实例一样。使用此解决方案,您可以在每个实例的基础上进行包装。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值