首页 > 后端开发 > Python教程 > 如何在 Python 中重写装饰器参数

如何在 Python 中重写装饰器参数

Susan Sarandon
发布: 2025-01-10 08:06:41
原创
652 人浏览过

How to Override Decorator Arguments in Python

要修改从父类继承的子类方法中的装饰器参数,您必须显式重写该方法本身。 简单地定义具有匹配名称的新类变量不会改变装饰器的行为。装饰器参数是在装饰方法时绑定的,而不是在实例化类时绑定的。

说明性示例

以下 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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板