允许在抽象类内使用用户定义的装饰器吗?还是应该在继承后使用它?

时间:2019-06-17 23:08:45

标签: python abstract-class python-decorators

例如,假设我有一个定义的装饰器,名为:$str = '$_POST["a_string_of_unspecified_length"][4]input&set1'; echo substr($str, 0, strpos($str, ']') + 1); // $_POST["a_string_of_unspecified_length"]

decorate

接下来,假设我正在编写一个名为Model的抽象类

def decorate(func):
  def inside_func(*args, **kwargs):
    # Do something
    return func(*args, **kwargs)
  return inside_func

或者应该是

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

如果两者都允许,是否有“最佳实践”方法?

1 个答案:

答案 0 :(得分:2)

都允许。因为abstractmethod,所以您在课堂上的decoratesomething都是函数。您可以将它们打印到控制台进行验证。

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的理解,做出自己的判断。