简体   繁体   English

Python函数注释中=运算符的作用是什么?

[英]What is the purpose of the = operator in Python function annotations?

From PEP 3107, http://www.python.org/dev/peps/pep-3107/#parameters , I've just noticed some extra syntax for function annotations that I wasn't aware of and don't quite understand. 从PEP 3107, http: //www.python.org/dev/peps/pep-3107/#parameters,我刚刚注意到了一些我不了解和不太了解的函数注释语法。

def foo(a: expression, b: expression = 5):
    ...

It's the second portion that I am uncertain about, expression = 5 . 这是我不确定的第二部分, expression = 5 How would you use that in a practical sense? 从实际意义上讲,您将如何使用它? Surely not to specify a default argument, which would already be self-evident. 一定不要指定默认参数,该参数已经不言而喻了。

The = 5 is not part of the annotation . = 5 不是注释的一部分 It is the default value for a keyword argument here. 这是关键字参数的默认值。

If you strip the annotations, what you have is: 如果删除注释,则将具有:

def foo(a, b = 5):

From the Function definition grammar : 根据函数定义语法

 parameter ::= identifier [":" expression] defparameter ::= parameter ["=" expression] 

where defparameter is a parameter in a function definition; defparameter是函数定义中的参数; the "=" expression follows parameter , and the definition for parameter includes the ":" expression section that defines an annotation. "=" expression如下parameter ,以及用于定义parameter包括":" expression部分限定了注释。

Quoting the original proposal, PEP 3107 : 引用原始提案,PEP 3107

Annotations for parameters take the form of optional expressions that follow the parameter name : 参数注释采用参数名称后面的可选表达式的形式:

 def foo(a: expression, b: expression = 5): ... 

In pseudo-grammar, parameters now look like identifier [: expression] [= expression] . 在伪语法中,参数现在看起来像identifier [: expression] [= expression] That is, annotations always precede a parameter's default value and both annotations and default values are optional. 也就是说, 注释始终在参数的默认值之前,并且注释和默认值都是可选的。

Emphasis mine. 强调我的。

这是参数“ b”的默认值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM