問題描述
我最近在查看 Python 3.3 語法規范時發現了一些有趣的東西:
I've recently noticed something interesting when looking at Python 3.3 grammar specification:
funcdef: 'def' NAME parameters ['->' test] ':' suite
Python 2 中沒有可選的箭頭"塊,我在 Python 3 中找不到任何有關其含義的信息.事實證明這是正確的 Python,并且被解釋器接受:
The optional 'arrow' block was absent in Python 2 and I couldn't find any information regarding its meaning in Python 3. It turns out this is correct Python and it's accepted by the interpreter:
def f(x) -> 123:
return x
我認為這可能是某種前置條件語法,但是:
I thought that this might be some kind of a precondition syntax, but:
- 我無法在此處測試
x
,因為它仍然未定義, - 無論我在箭頭后面放什么(例如
2 < 1
),它都不會影響函數的行為.
- I cannot test
x
here, as it is still undefined, - No matter what I put after the arrow (e.g.
2 < 1
), it doesn't affect the function behavior.
熟悉這種語法風格的人能解釋一下嗎?
Could anyone familiar with this syntax style explain it?
推薦答案
這是一個函數注釋.
更詳細地說,Python 2.x 有文檔字符串,允許您將元數據字符串附加到各種類型的對象.這非常方便,因此 Python 3 通過允許您將元數據附加到描述其參數和返回值的函數來擴展該功能.
In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.
沒有先入為主的用例,但 PEP 建議了幾個.一種非常方便的方法是允許您使用預期類型注釋參數;然后很容易編寫一個裝飾器來驗證注釋或將參數強制為正確的類型.另一個是允許特定參數的文檔,而不是將其編碼到文檔字符串中.
There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.
這篇關于什么->在 Python 函數定義中是什么意思?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!