最近在查看Python 3.3语法规范时,我注意到一些有趣的事情:
funcdef: 'def' NAME parameters ['->' test] ':' suite
可选的“箭头”块在Python 2中不存在,我在Python 3中找不到关于它的含义的任何信息。事实证明这是正确的Python,它被解释器接受:
def f(x) -> 123:
return x
我认为这可能是一种前提语法,但是:
我不能在这里测试x,因为它仍然没有定义,
无论我在箭头后面放什么(例如2 < 1),它都不会影响函数的行为。
熟悉这种语法风格的人能解释一下吗?
它只是告诉用户它期望什么或返回什么值
funcname。__annotations__将打印细节
like
def function(name:str ,age:int) -> "printing the personal details ":
print(f"name is {name} age is {age}")
function("test",20)
print(function.__annotations__)
输出
name is test age is 20
{'name': <class 'str'>, 'age': <class 'int'>, 'return': 'printing the personal details '}
即使您返回值,它也不显示任何内容。