首页 > 解决方案 > 覆盖函数装饰器参数

问题描述

我有一个基类和一个子类。Base class有一个传递给装饰器的类变量。现在,当我将 Base 继承到 child 并更改变量值时,装饰器不会获取over-ride类变量值。

这是代码: -

class Base():   
    variable = None

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

class Child(Base):
    variable = 1

无需再次覆盖该函数:如何将子类变量传递给装饰器?

标签: python

解决方案


deceze 的评论已经解释了为什么这没有反映在子类中。

一种解决方法是,您可以在装饰器端构建逻辑。

即,像这样的东西。

 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(variable=variable)to更新为@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`.

推荐阅读