繁体   English   中英

覆盖函数装饰器参数

[英]Override function decorator argument

我有一个基础班和一个儿童班。 Base class具有传递给装饰器的类变量。 现在,当我将Base继承为child并更改变量值时,装饰器不会采用over-ride类的变量值。

这是代码:

class Base():   
    variable = None

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

class Child(Base):
    variable = 1

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

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)装饰器语法从@decorator(variable=variable)@decorator(variable='variable')

class Base:

    variable = None

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

DEMO

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

让我们尝试一下子类

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM