最近在查看Python 3.3语法规范时,我注意到一些有趣的事情:

funcdef: 'def' NAME parameters ['->' test] ':' suite

可选的“箭头”块在Python 2中不存在,我在Python 3中找不到关于它的含义的任何信息。事实证明这是正确的Python,它被解释器接受:

def f(x) -> 123:
    return x

我认为这可能是一种前提语法,但是:

我不能在这里测试x,因为它仍然没有定义, 无论我在箭头后面放什么(例如2 < 1),它都不会影响函数的行为。

熟悉这种语法风格的人能解释一下吗?


当前回答

这意味着函数返回的结果类型,但它可以是None。

它在面向Python 3.x的现代库中广泛存在。

例如,它在很多地方的库panda -profiling代码中有:

def get_description(self) -> dict:

def get_rejected_variables(self, threshold: float = 0.9) -> list:

def to_file(self, output_file: Path or str, silent: bool = True) -> None:
"""Write the report to a file.

其他回答

在以下代码中:

def f(x) -> int:
    return int(x)

-> int只是告诉f()返回一个整数(但它不强制函数返回一个整数)。它被称为返回注释,可以通过f.__annotations__['return']访问。

Python还支持参数注释:

def f(x: float) -> int:
    return int(x)

: float告诉阅读程序(以及一些第三方库/程序,例如pylint)的人x应该是浮点数。它被访问为f.__annotations__['x'],本身没有任何意义。更多信息请参阅文档:

https://docs.python.org/3/reference/compound_stmts.html#function-definitions https://www.python.org/dev/peps/pep-3107/

这意味着函数返回的结果类型,但它可以是None。

它在面向Python 3.x的现代库中广泛存在。

例如,它在很多地方的库panda -profiling代码中有:

def get_description(self) -> dict:

def get_rejected_variables(self, threshold: float = 0.9) -> list:

def to_file(self, output_file: Path or str, silent: bool = True) -> None:
"""Write the report to a file.

def函数(arg) - > 123:

它只是一个返回类型,这里的整数与你写的数字无关。

比如Java:

public int function(int args){...}

但是对于Python (Jim Fasarakis Hilliard)来说,返回类型只是一个提示,所以它建议返回,但无论如何允许返回其他类型,比如字符串。

->在python3中被引入。

简单地说,->后面的内容表示函数的返回类型。 返回类型是可选的。

请参考PEP3107规范。这些是函数注释。Python 2。X有文档字符串。类似地,Python 3引入了->作为函数注释的使用。Python在生成文档时使用这些。