簡體   English   中英

Python函數注釋中=運算符的作用是什么?

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

從PEP 3107, http: //www.python.org/dev/peps/pep-3107/#parameters,我剛剛注意到了一些我不了解和不太了解的函數注釋語法。

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

這是我不確定的第二部分, expression = 5 從實際意義上講,您將如何使用它? 一定不要指定默認參數,該參數已經不言而喻了。

= 5 不是注釋的一部分 這是關鍵字參數的默認值。

如果刪除注釋,則將具有:

def foo(a, b = 5):

根據函數定義語法

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

defparameter是函數定義中的參數; "=" expression如下parameter ,以及用於定義parameter包括":" expression部分限定了注釋。

引用原始提案,PEP 3107

參數注釋采用參數名稱后面的可選表達式的形式:

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

在偽語法中,參數現在看起來像identifier [: expression] [= expression] 也就是說, 注釋始終在參數的默認值之前,並且注釋和默認值都是可選的。

強調我的。

這是參數“ b”的默認值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM