修改 python 可调用函数,使其调用 before() ,然后调用实际函数 after()
我不确定这是否是在函数 f1()
周围调用 before
和 after
函数的最佳方式。
class ba(object):
def __init__(self, call, before, after):
self.call = call
self.before = before
self.after = after
def __call__(self, *args):
self.before()
r = self.call(*args)
self.after()
return r
class test1(object):
def mybefore(self):
print "before func call"
def myafter(self):
print "after func call"
def meth1(a1, a2):
print "meth1(a1=%d, a2=%d)" % (a1, a2)
t = test1()
wmeth1 = ba(meth1, t.mybefore, t.myafter)
wmeth1(1, 2)
请指教。
I am not sure if this is the best way to have before
and after
functions be called around a function f1()
.
class ba(object):
def __init__(self, call, before, after):
self.call = call
self.before = before
self.after = after
def __call__(self, *args):
self.before()
r = self.call(*args)
self.after()
return r
class test1(object):
def mybefore(self):
print "before func call"
def myafter(self):
print "after func call"
def meth1(a1, a2):
print "meth1(a1=%d, a2=%d)" % (a1, a2)
t = test1()
wmeth1 = ba(meth1, t.mybefore, t.myafter)
wmeth1(1, 2)
Please advise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会使用装饰器,如下所示:
I'd use a decorator, like so:
您可以在
contextlib
模块中使用@contextmanager
装饰器以及with
语句来实现以下目的:You could use the
@contextmanager
decorator in thecontextlib
module along with awith
statement for something along these lines: