什么时候使用Python省略号优于“通过”?

时间:2019-03-21 06:36:37

标签: python

当我发现abc模块(https://docs.python.org/3/library/abc.html)时,我只是在寻找定义Python抽象基类的方法。

稍作阅读后,我看到了以下课程:

class C(ABC):
    @abstractmethod
    def my_abstract_method(self, ...):
        ...
    @classmethod
    @abstractmethod
    def my_abstract_classmethod(cls, ...):
        ...

关于三点,我发现它叫做Ellipsishttps://docs.python.org/3/library/constants.html#Ellipsis)很奇怪。到目前为止,我只在与类型提示结合使用时才看到并使用它,在这种情况下,它非常有意义。

但是为什么要在抽象方法的定义中使用省略号呢?就个人而言,我要么做

def my_abstract_method(self):
    raise RuntimeError("NotImplemented")

def my_abstract_method(self):
    pass

那么为什么在官方文档中省略号优于pass?只是有意见吗?

2 个答案:

答案 0 :(得分:0)

使用Ellipsis文字作为函数的主体不会执行任何操作。如果使用它而不是pass或其他语句,则完全是样式问题。如果为函数提供文档字符串,则甚至无需在文档字符串的行后放置 any 语句。

如果官方的Python文档不一致,则可能是因为编写文档的Python核心开发人员本身对哪种外观最好没有统一的看法。 PEP 8对于使用伪函数的主体没有给出任何建议(尽管它确实使用了许多...来代替其示例中的东西,有时在某些地方您实际上不能在真实代码中使用Ellipsis

因此对于您自己的代码,请使用最喜欢的代码。如果您想对此保持正式态度,请在样式指南中写下您的偏好,然后始终按照指南的指示进行操作。您不需要遵循与其他任何人相同的风格(除非该人是您的老板)。

最后一点:您不能在函数定义中使用...作为参数名称(def my_abstract_method(self, ...):引发SyntaxError,无论下一行是什么)。

答案 1 :(得分:0)

我查看了 ql.Date (3.7) 文档和

python

pydoc ...
The Ellipsis Object
*******************

This object is commonly used by slicing (see Slicings).  It supports
no special operations.  There is exactly one ellipsis object, named
"Ellipsis" (a built-in name).  "type(Ellipsis)()" produces the
"Ellipsis" singleton.

It is written as "Ellipsis" or "...".

Related help topics: SLICINGS

所以至少从 pydoc pass The "pass" statement ******************** pass_stmt ::= "pass" "pass" is a null operation Ś when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example: def f(arg): pass # a function that does nothing (yet) class C: pass # a class with no methods (yet) 的角度来看,pydoc 是定义什么都不做的函数的方式。