重写函数decorator参数

2024-04-24 01:00:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个基类和一个子类。Base class有一个传递给decorator的类变量。现在,当我将Base继承到child并更改变量值时,decorator不接受over-ride类变量值。你知道吗

这是你的答案代码:-你知道吗

class Base():   
    variable = None

    @decorator(variable=variable)
    def function(self):
        pass

class Child(Base):
    variable = 1

不再次重写函数:如何将子类变量传递给decorator?你知道吗


Tags: 答案代码selfnonechildbasedeffunction
1条回答
网友
1楼 · 发布于 2024-04-24 01:00:38

deceze的评论已经解释了为什么这没有反映在子类上。你知道吗

一种解决方法是,您可以在decorator端构建逻辑。你知道吗

像这样的。你知道吗

 def decorator(_func=None, *, variable):
    def decorator_func(func):
        def wrapper(self, *args, **kwargs):
            variable_value = getattr(self.__class__, variable)
            print(variable_value)
            # You can use this value to do rest of the work.
            return func(self, *args, **kwargs)
        return wrapper

    if _func is None:
        return decorator_func
    else:
        return decorator_func(_func)

同时将decorator语法从@decorator(variable=variable)更新为@decorator(variable='variable')

class Base:

    variable = None

    @decorator(variable='variable')
    def function(self):
        pass

演示

b = Base()
b.function() # This will print `None`.

让我们试试子类

b = Child()
b.function() # This will print `1`.

相关问题 更多 >