要修改从父类继承的子类方法中的装饰器参数,您必须显式重写该方法本身。 简单地定义具有匹配名称的新类变量不会改变装饰器的行为。装饰器参数是在装饰方法时绑定的,而不是在实例化类时绑定的。
说明性示例
以下 Python 代码 (test.py
) 演示了这一点:
<code class="language-python">def my_decorator_with_args(param1, param2): """Decorator accepting arguments""" def actual_decorator(func): def wrapper(self, *args, **kwargs): print(f"[Decorator] param1={param1}, param2={param2}") return func(self, *args, **kwargs) return wrapper return actual_decorator class BaseClass: @my_decorator_with_args(param1="BASE_PARAM1", param2="BASE_PARAM2") def greet(self): print("Hello from BaseClass!") class DerivedClass(BaseClass): """ Attempting to override decorator arguments via class variables; however, since `greet()` isn't redefined, the parent's decorator remains active. """ param1 = "DERIVED_PARAM1" param2 = "DERIVED_PARAM2" class DerivedClassOverride(BaseClass): """ Correctly overrides `greet()` to utilize modified decorator arguments. """ @my_decorator_with_args(param1="OVERRIDE_PARAM1", param2="OVERRIDE_PARAM2") def greet(self): print("Hello from DerivedClassOverride!") if __name__ == "__main__": print("=== BaseClass's greet ===") b = BaseClass() b.greet() print("\n=== DerivedClass's greet (no override) ===") d = DerivedClass() d.greet() print("\n=== DerivedClassOverride's greet (with override) ===") d_o = DerivedClassOverride() d_o.greet() </code>
执行python test.py
会产生:
<code>=== BaseClass's greet === [Decorator] param1=BASE_PARAM1, param2=BASE_PARAM2 Hello from BaseClass! === DerivedClass's greet (no override) === [Decorator] param1=BASE_PARAM1, param2=BASE_PARAM2 Hello from BaseClass! === DerivedClassOverride's greet (with override) === [Decorator] param1=OVERRIDE_PARAM1, param2=OVERRIDE_PARAM2 Hello from DerivedClassOverride!</code>
这清楚地表明,只有在子类中重新定义方法(greet
)才能成功覆盖装饰器的参数。
以上是如何在 Python 中重写装饰器参数的详细内容。更多信息请关注PHP中文网其他相关文章!