python - 覆盖函数装饰器参数
问题描述
我有一个基类和一个子类。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)
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`.
推荐阅读
- java - 我可以在自动化测试期间从 HttpRequest 捕获 JSON 有效负载(JUnit 或带有 Selenium 的 TestNG)吗?
- vba - 我可以在 vba 中使用哪个函数,类似于我在 sql 中使用的函数
- c# - .NET 字典插入的奇怪性能行为
- swift - 带有复选框的 SwiftUI ToDoList?
- javascript - html-webpack-plugin - 脚本注入问题
- android - 条目名称“classes.dex”发生冲突
- javascript - 按顺序异步每一行,等待它返回
- c# - 反序列化 JSON 错误:类型需要 JSON 对象
- clang - libc++ 是否向后兼容旧版本?
- django - django 联系页面错误地发送电子邮件