python在类内部使用装饰器_python – 如何在类中使用装饰器

我知道有类似的问题,但我的情况有些不同:参考代码:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值