[英]Use inherited method from parent class as decorator on child classes method
我正在嘗試在 A 類中設置一個方法,該方法可以在子類 B 中用作方法的裝飾器。 我想根據某些實例屬性將參數映射到這些函數。
在同一個類中這樣做可以正常工作:
class Class:
def __init__(self):
self.mapper = "mapped "
def map_arg(func):
def mapped_func(self, unmapped_value):
mapped_value = self.mapper + unmapped_value
return func(self, mapped_value)
return mapped_func
@map_arg
def func(self, mapped_value):
print(mapped_value)
obj = Class()
obj.func("value")
打印mapped value
。 但是當我嘗試繼承裝飾器時,它會拋出一個NameError
class ParentClass:
def map_arg(func):
def mapped_func(self, unmapped_value):
mapped_value = self.mapper + unmapped_value
return func(self, mapped_value)
return mapped_func
class ChildClass(ParentClass):
def __init__(self):
self.mapper = "mapped "
@map_arg
def func(self, mapped_value):
print(mapped_value)
obj = ChildClass()
obj.func("value")
Traceback (most recent call last):
File "/tmp/decorator.py", line 43, in <module>
class ChildClass(ParentClass):
File "/tmp/decorator.py", line 47, in ChildClass
@map_arg
NameError: name 'map_arg' is not defined
我也試過使用@super().map_arg
,但這是一個語法錯誤。 我想在函數中調用self.map_arg
而不是將它包裝在裝飾器中更容易。 但是有沒有辦法讓它發揮作用?
您只需要使用父類的名稱:
class ChildClass(ParentClass):
def __init__(self):
self.mapper = "mapped "
@ParentClass.map_arg
def func(self, mapped_value):
print(mapped_value)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.