使用参数访问基于类的装饰器的属性

时间:2017-01-26 18:12:27

标签: python properties python-decorators

假设我有一个基于类的装饰器,其参数如下:

class Decorator:
    def __init__(self, arg):
        self.arg = arg

    def __call__(self, func):
        def wrap():
            # something with self.arg
            func()
        return wrap

当我有一个装饰函数foo时,我可以执行以下操作:

deco = Decorator("ARG")
def foo():
    pass
foo = deco(foo)
deco.arg = "CHANGE ARG"

如果我使用deco.arg - 语法,可以通过某种方式访问​​/更改@吗?

@Decorator("ARG")
def foo():
    pass

# How to change/access the arg-attribute?

1 个答案:

答案 0 :(得分:1)

你可以创建一个闭包:

def Decorator(arg):
    class InnerDecorator:
        def __init__(self, func):
            self.func = func
            # make arg an instance attribute
            self.arg = arg  

        def __call__(self):
            return self.func()

    return InnerDecorator

@Decorator("ARG")
def foo():
    pass

然后在函数上设置属性:

>>> foo.arg
'ARG'
>>> foo.arg = 'WOW'
>>> foo.arg
'WOW'