让我说我的类有很多方法,我想在每一个方法上应用我的装饰,后来当我添加新方法时,我想要应用相同的装饰器,但我不想在方法声明之上写@mydecorator所有时间?
如果我调查的__call__是正确的方法吗?
重要提示:以下示例似乎解决了与原始问题不同的问题.
编辑:我想以这种方式展示,这是我的问题的类似解决方案,对于任何人后来发现这个问题,使用评论中提到的mixin.
class WrapinMixin(object):
def __call__(self, hey, you, *args):
print 'entering', hey, you, repr(args)
try:
ret = getattr(self, hey)(you, *args)
return ret
except:
ret = str(e)
raise
finally:
print 'leaving', hey, repr(ret)
Run Code Online (Sandbox Code Playgroud)
然后你可以在另一个
class Wrapmymethodsaround(WrapinMixin):
def __call__:
return super(Wrapmymethodsaround, self).__call__(hey, you, *args)
Run Code Online (Sandbox Code Playgroud) 我需要将 lambda 函数分配给一个变量,并稍后在脚本中使用它来进行小型保护。那可能吗?
\n例如,I\xc2\xb4ll 将 lambda 函数分配给名为 foo 的变量:
\nfoo = lambda\nRun Code Online (Sandbox Code Playgroud)\n然后,当我需要它时,我会这样或那样地使用它:
\nfoo2 = foo x: x*x\nRun Code Online (Sandbox Code Playgroud)\n这可能吗?
\n