类方法的Python装饰器不接受来自类属性的参数

问题描述 投票:0回答:1

我有一个条件装饰器,如果传递“True”则执行操作,它在独立函数上效果很好,但是当尝试在类方法上使用它时,我无法传递来自类属性的参数。

以下是它在独立函数上的工作原理:

# decorator with arguments
class MyDec(object):
    def __init__(self,flag):
        self.verbose = flag
    def __call__(self, original_func):
        decorator_self = self
        def wrapper( *args, **kwargs):
            if decorator_self.verbose:
                print('in decorator action')
            original_func(*args,**kwargs)
        return wrapper


@MyDec(True)
def bar():
    print ('in function (decorated) action')

bar()

# output
'''
in decorator action
in function (decorated) action
'''

@MyDec(False)
def bar():
    print ('in function (decorated) action')

bar()

# output
'''
in function(decorated) action
'''

但是当我尝试在类方法上使用 in 时,我无法从类 init 属性传递详细参数:

class One:
    def __init__(self, verbose):
        self.verbose = verbose

    @MyDec(self.verbose)
    def print_something(self):
        print('in decorated func action')

one = One(False)
one.print_something()

# output
'''
NameError: name 'self' is not defined
'''

我尝试创建全局变量/局部变量并传递它们,但没有任何效果。请帮忙。

python arguments decorator verbose
1个回答
0
投票

当类主体要被执行时,您会收到该错误。在那个阶段,你甚至没有

One
类的任何实例,因此
self
不能存在。

就像global中的其他函数一样,传递实际值:

class One:
    def __init__(self, verbose):
        self.verbose = verbose

    @MyDec(True)
    def print_something(self):
        print("in decorated func action")

您的方法不能依赖于实例的值。方法创建发生在任何实例创建之前。

© www.soinside.com 2019 - 2024. All rights reserved.