[英]Use method from superclass as "decorator" for subclass
我有一個場景,我想在 python 的子類中“標記”方法,基本上說“將此子類方法包裝在超類中的方法中”
例如:
class SuperClass:
...
def wrapping_method(func):
# do something in the SuperClass instance before the method call
func(args)
# do something in the SuperClass instance after the method call
...
class SubClass(SuperClass):
...
def my_function(args):
# do something in the SubClass instance
...
我想要這樣,每當我在 SubClass 中調用my_function(args)
時,都會調用 SuperClass 中的wrapping_method()
方法,而不是使用作為參數傳入的方法my_function
(以某種方式使用所有my_function
參數)。
我不熟悉如何在這里使用裝飾器之類的東西,但我希望能夠使用某種類似注釋的“@”符號來“標記”子類方法。
使用裝飾器和子類化是正交的。 您可以在基類方法(或您喜歡的任何地方)中定義裝飾器並將其應用於子類方法(或您喜歡的任何地方)。
class SuperClass:
"""Type that counts invocation of methods decorated with @counted"""
def __init__(self):
self.count = 0
# define decorator by taking one callable as argument
@staticmethod
def counted(method): # 1
"""Decorate a method to count its invocations"""
def counted_method(self, *args, **kwargs):
self.count += 1
bound_method = method.__get__(type(self), self) # 2
return bound_method(*args, **kwargs)
return counted_method
class SubClass(SuperClass):
# use `@decorator` to decorate a method
@SuperClass.counted
def my_method(self):
print("doing something in the SubClass instance")
在這里, counted
是一個普通的裝飾器,這意味着它只需要一些可調用的( #1
)並對其執行一些操作——在這個例子中,包裝它。 由於counted_method
包含實際方法,我們必須手動調用描述符協議( #2
) 來模擬方法查找。
>>> instance = SubClass()
>>> instance.count
0
>>> instance.my_method()
doing something in the SubClass instance
>>> instance.count
1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.