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

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

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

def f(x) -> 123:
    return x

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

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

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


当前回答

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

其他回答

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

def f(x) -> str:
return x+4

print(f(45))

将给出结果:49。

换句话说,'-> str'对返回类型没有影响:

print(f(45).__class__)

<class 'int'>
def f(x) -> 123:
    return x

我的总结:

Simply -> is introduced to get developers to optionally specify the return type of the function. See Python Enhancement Proposal 3107 This is an indication of how things may develop in future as Python is adopted extensively - an indication towards strong typing - this is my personal observation. You can specify types for arguments as well. Specifying return type of the functions and arguments will help in reducing logical errors and improving code enhancements. You can have expressions as return type (for both at function and parameter level) and the result of the expressions can be accessed via annotations object's 'return' attribute. annotations will be empty for the expression/return value for lambda inline functions.

它是一个函数注释。

更详细的,Python 2。X具有文档字符串,允许您将元数据字符串附加到各种类型的对象。这非常方便,所以Python 3扩展了这个特性,允许你将元数据附加到函数上,描述它们的参数和返回值。

没有先入为主的用例,但是PEP建议了几个用例。一个非常方便的方法是允许你用参数的预期类型来注释参数;这样就很容易编写一个装饰器来验证注释或将参数强制转换为正确的类型。另一种是允许特定于参数的文档,而不是将其编码到文档字符串中。

def函数(arg) - > 123:

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

比如Java:

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

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