[英]write a python decorator inside an abstract class and use it in an inherited class
[英]Is it permitted to use a user defined decorator inside an abstract class? Or, should it be used after inheritance?
例如,假設我有一個定義的裝飾器,稱為: decorate
def decorate(func):
def inside_func(*args, **kwargs):
# Do something
return func(*args, **kwargs)
return inside_func
接下來,假設我正在編寫一個名為Model的抽象類
from abc import ABC, abstractmethod
class Model(ABC):
def __init__(self, value):
self.value = value
super().__init__()
@abstractmethod
@decorate # <-------------------- IS @decorate ALLOWED HERE?
def do_something(self):
pass
或者,應該是:
from abc import ABC, abstractmethod
class Model(ABC):
def __init__(self, value):
self.value = value
super().__init__()
@abstractmethod
def do_something(self):
pass
# Inherit the base class
class DoAdd42(Model):
@decorate # <----------------------- SHOULD @decorate BE HERE INSTEAD?
def do_something(self):
return self.value + 42
如果兩者都允許,是否有“最佳實踐”方法?
兩者都允許。 因為abstractmethod
,您的decorate
和類中的something
都是函數。 您可以將它們打印到控制台進行驗證。
In [2]: def decorate(func):
...: def inside_func(*args, **kwargs):
...: # Do something
...: return func(*args, **kwargs)
...: return inside_func
...:
In [7]: from abc import ABC, abstractmethod
...:
...: class Model(ABC):
...: def __init__(self, value):
...: self.value = value
...: super().__init__()
...:
...: @abstractmethod
...: @decorate # <-------------------- IS @decorate ALLOWED HERE?
...: def do_something(self):
...: pass
...: # even no self is valid for class in Python3+
...: def whatever():
...: print('fff')
...:
In [8]: print(abstractmethod)
<function abstractmethod at 0x100ff86a8>
In [9]: print(Model.do_something)
<function decorate.<locals>.inside_func at 0x1041031e0>
In [10]: print(Model.whatever)
<function Model.whatever at 0x103b48950>
In [11]: Model.whatever()
fff
我對abstractmethod
並不熟悉,所以我不了解最佳實踐以及有關其規則的更多詳細信息。 您可以根據我提供的信息並結合自己對abstractmethod
的理解,嘗試做出自己的判斷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.