我知道有类似的问题,但我的情况有些不同:参考代码:
class MyClass(object):
def __init__(self, log_location)
self.logs = logging(log_location) # create log object by the log_location, this object should be used by the decorator fucntion
def record_log(log_object):
""" this is the decorator function
"""
def deco(func):
def wrap(*args, **kwargs):
rs = func()
# use log object to record log
if rs:
log_object.record('success')
else:
log_object.record('fail')
return wrap
return deco
@record_log(self.logs)
def test(self):
rs = do_some_thing
if rs:
return True
return False
def main():
my_class = MyClass()
my_class.test()
但是,有这样的错误:
@record_log(self.logs)
NameError: name 'self' is not defined
我应该在这样的场景中使用装饰器函数中的实例属性self.logs吗?
非常感谢!
最佳答案 您的代码有几个异议:
> deco()是多余的.您可以直接从record_log()返回换行.
>如果您只打算装饰MyClass的方法,那么将log_object传递给装饰器是没有意义的,因为将始终使用self.logs.否则,考虑将装饰器移动到模块级别,如其他人已经建议的那样.
>装饰方法的返回值当前丢失.
>对装饰函数的调用不会将self传递给它.
因此,正确的代码是:
class MyClass(object):
def __init__(self, log_location):
self.logs = logging(log_location)
def record_log(func):
""" this is the decorator function
"""
def wrap(self):
rs = func(self)
# use log object to record log
if rs:
print 1
self.logs.record('success')
else:
print 2
self.logs.record('fail')
return rs
return wrap
@record_log
def test(self):
rs = do_some_thing
if rs:
return True
return False