Python 3.5中的抽象方法的主体 [英] Body of abstract method in Python 3.5

查看:92
本文介绍了Python 3.5中的抽象方法的主体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类Model,其中包含一些抽象方法,我应该在方法主体中添加什么?

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

  1. 退货

  1. A return

class Model(metaclass=ABCMeta):
    @abstractmethod
    def foo(self): return

  • 通行证

  • A pass

    class Model(metaclass=ABCMeta):
        @abstractmethod
        def foo(self): pass
    

  • 引发描述性错误

  • 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__))
    

  • 通常,我将实现方法3并引发错误,但是由于Python为我引发了错误,因此这似乎是多余的:

    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
    

    在给出的选项之间,哪种是最佳做法?还是我还有其他方法可以解决这个问题?

    推荐答案

    放置在abstractmethod(或abstractproperty)正文中的最佳方法是文档字符串.

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

    那么您就不需要passreturn...了,因为其中隐含了return None-并且文档字符串使此结构可以在没有SyntaxError的情况下编译":

    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.

    这篇关于Python 3.5中的抽象方法的主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆