【问题标题】:How to access class variable in decorator function如何在装饰器函数中访问类变量
【发布时间】:2019-12-21 14:50:57
【问题描述】:

是否可以创建一个不带参数的装饰器函数来访问类变量。我发现了类似的问题,但它们总是引用实例变量而不是类变量,并且这些变量通常仅在调用装饰方法时才被访问。

我想在类定义而不是实例化之后引用类变量。

我想到了其他解决方案,例如创建 Meta 类,但我只想使用一个类和一个不带参数的装饰器。

我能够在不使用装饰器的情况下通过以下方式实现所需的功能并获得所需的结果。

class B:
    b=3
    resetFuns=[]

    def __init__(self,x):
        self.x=x
        self.y=x+self.b


    def foo(self):
        self.y=self.x+self.b

    resetFuns.append(foo)

    def reset(self):
        for f in self.resetFuns:
            f(self)

test=B(4)
print(test.y)
B.b=9
print(test.y)
test.reset()
print(test.y)

7
7
13

但我想使用类似这样的装饰器。

class A:
    b=3
    resetFuns=[] ##class variable I want to access

    def __init__(self,x):
        self.x=x
        self.y=x+self.b

    def resetDecorator(func):
        resetFuns.append(func) ##can't reference resetFuns like this 
        return func

    @resetDecorator
    def foo(self):
        self.y=self.x+self.b

    def reset(self):
        for f in resetFuns:
            f(self)

【问题讨论】:

    标签: python class oop python-decorators


    【解决方案1】:

    类似:

    def resetDecoratorCreator(resetFuns):
        def resetDecorator(func):
            resetFuns.append(func)
            return func
        return resetDecorator
    
    class B:
        b=3
        resetFuns=[]
        resetDecorator = resetDecoratorCreator(resetFuns)
    
        def __init__(self,x):
            self.x=x
            self.y=x+self.b
    
        @resetDecorator
        def foo(self):
            self.y=self.x+self.b
    
        def reset(self):
            for f in self.resetFuns:
                f(self)
    

    会得到你想要的。

    【讨论】:

      猜你喜欢
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 2016-02-08
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 2020-12-04
      相关资源
      最近更新 更多