【发布时间】:2017-10-15 08:39:23
【问题描述】:
是否可以在python中装饰__getattr__之类的方法?
像这样
@myWrapper
def __getattr__(self,attrName):
'''
myCode Goes here
'''
当我尝试使用类似上面的东西时,我遇到了一些错误:
感谢威廉指出..
我发现了我在代码中犯的错误。
我的意图是做这样的事情
class A:
def __init__(self):
self.a=someObject()
@mywrapper
def __getattr__(self,argName):
# call self.a 's method. If that doesnt have
# then raise an exception
所以我的方法可能有一些参数,我也需要传递它..
所以我写了这样的东西来测试:
class A:
def __init__(self):
self.a=someObject()
@mywrapper
def __getattr__(self,argName):
print('getAttr called for {}'.format(argName))
def mymethod(*args,**kwargs):
import ipdb;ipdb.set_trace()
return mymethod
我的包装代码如下所示:
def mywrapper(method):
def methodWrapper(obj,name):
print("In decorator for {}".format(method));
method(obj,name)
return methodWrapper
但是当我像 obj.c(1) 一样执行时,我得到以下异常
TypeError: 'NoneType' object is not callable
事实上,装饰器和__getattr__ 中的打印语句都在执行,但我看到了异常..
如何解决?
【问题讨论】:
-
请粘贴您的装饰器的代码
-
当然。
myWrapper到底在做什么?
标签: python python-3.x python-decorators