要修改從父類別繼承的子類別方法中的裝飾器參數,您必須明確重寫該方法本身。 簡單地定義具有匹配名稱的新類別變數不會改變裝飾器的行為。裝飾器參數是在裝飾方法時綁定的,而不是在實例化類別時綁定的。
說明性範例
以下 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中文網其他相關文章!