代码之家  ›  专栏  ›  技术社区  ›  brohan322

强制子类写入docstring

  •  0
  • brohan322  · 技术社区  · 5 年前

    我实现了一个抽象类:

    from abc import ABC, abstractmethod
    
    class Study(ABC):
    
       """ Define the purpose of the study here """
    
       def __init__(self, value):
          self.value = value
    
       @abstractmethod
       def do_something(self):
          pass
    

    我还实现了一个子类:

    class PilotStudy(Study):
    
       def do_something(self):
          print('Pilot Study')
    

    我想强制子类在类定义下面定义一个docstring。有没有一种方法可以做到这一点(这样,我在上面定义的子类会抛出一个错误,因为该类中没有docstring)?

    2 回复  |  直到 5 年前
        1
  •  4
  •   chepner    5 年前

    使用 __init_subclass__ . 这个 __doc__ 类的属性设置为类的docstring的值;如果没有docstring,则属性设置为 None

    class Study(ABC):
    
       """ Define the purpose of the study here """
    
       def __init__(self, value):
          self.value = value
    
       @abstractmethod
       def do_something(self):
          pass
    
       def __init_subclass__(cls):
          if cls.__doc__ is None:
              raise AttributeError("No docstring")
    

    那么

    >>> class GoodStudy(Study):
    ...   "Do some stuff"
    ...
    >>> class BadStudy(Study):
    ...   pass
    ...
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<path>/abc.py", line 126, in __new__
        cls = super().__new__(mcls, name, bases, namespace, **kwargs)
      File "tmp.py", line 16, in __init_subclass__
        raise AttributeError("No docstring")
    AttributeError: No docstring