【发布时间】:2016-03-08 20:11:08
【问题描述】:
想知道是否有人有一个好的方法来动态检查一个类的函数类型,然后动态地将装饰器修补到其中一些函数上。我正在尝试这个,但没有得到我期望的结果。遍历类中的方法似乎有效,但做猴子补丁本身似乎失败了。任何想法都非常感谢!
def decorator(callable):
pass
class Test(object):
def foo1(self):
return self.bar()
def foo2(self):
return self.blah()
def foo3(self):
return 0
for x,y in Test.__dict__.items():
if type(y) == FunctionType:
Test.x = decorator(Test.x)
【问题讨论】:
-
这种动态添加装饰器的方法是完全有效的。我也希望 Python 有更好的语法,但目前应该没问题。
标签: python python-decorators monkeypatching