Body of abstract method in Python 3.5 [duplicate]

一曲冷凌霜 提交于 2020-01-01 02:52:28

问题


I have an abstract class, Model, with a few abstract methods, what should I put in the body of the methods?

  1. A return

    class Model(metaclass=ABCMeta):
        @abstractmethod
        def foo(self): return
    
  2. A pass

    class Model(metaclass=ABCMeta):
        @abstractmethod
        def foo(self): pass
    
  3. Raising a descriptive error

    class Model(metaclass=ABCMeta):
        @abstractmethod
        def foo(self):
            raise NotImplementedError("Class {class_name} doesn't implement {func_name} function"
                                  .format(class_name=self.__class__.__name__, func_name=self.foo.__name__))
    

Typically I would implement method 3 and raise an error, however it looks like it would be redundant, as Python raises an error for me:

>>> bar = module.Model()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Model with abstract methods foo

Between the options presented, which is best practice? Or is there another way I should handle this?


回答1:


The best thing to put in the body of an abstractmethod (or abstractproperty) would be a docstring.

Then you don't need pass or return or ... because a return None is implicitly included - and a docstring makes this construct "compile" without a SyntaxError:

from abc import abstractmethod, ABCMeta

class Model(metaclass=ABCMeta):
    @abstractmethod
    def foo(self):
        """This method should implement how to foo the model."""

The docstring should then explain what should be implemented here so that subclassers know what is/was intended.



来源:https://stackoverflow.com/questions/45826692/body-of-abstract-method-in-python-3-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!