简体   繁体   English

什么 - >在python中做

[英]What does -> do in python

I saw a python example today and it used -> for example this was what I saw: 我今天看到了一个python示例,它使用了 - >例如,这就是我所看到的:

spam = None
bacon = 42
def monty_python(a:spam,b:bacon) -> "different:":
    pass

What is that code doing? 这段代码在做什么? I'm not quite sure I've never seen code like that I don't really get what 我不太确定我从来没有见过这样的代码我真的没有得到什么

 a:spam,b:bacon  

is doing either, can someone explain this for me? 正在做什么,有人可以为我解释这个吗? I googled, "what does -> do in python" but no good searches came up that I found. 我用谷歌搜索,“在python中做了什么 - >做了什么”但是我找不到好的搜索。

It is function annotation for a return type. 它是返回类型的函数注释。 annotations do nothing inside the code, they are there to help a user with code completion (in my experience). annotations在代码中没有任何作用,它们可以帮助用户完成代码(根据我的经验)。

Here is the PEP for it. 这是它的PEP

Let me demonstrate, what I mean by "annotations do nothing inside the code". 让我演示一下,我所说的“注释在代码中什么都不做”。 Here is an example: 这是一个例子:

def fun(a: str, b: int) -> str:
    return 1

if __name__ == '__main__':
    print(fun(10, 10))

The above code will run without any errors. 上面的代码将运行没有任何错误。 but as you can see the first parameter should be a string , and the second an int . 但是你可以看到第一个参数应该是一个string ,第二个参数应该是一个int But, this only is a problem in my IDE, the code runs just fine: 但是,这只是我的IDE中的一个问题,代码运行得很好:

在此输入图像描述

They're function annotations . 它们是功能注释 They don't really do anything by themselves, but they can be used for documentation or in combination with metaprogramming. 它们本身并没有真正做任何事情,但它们可以用于文档或与元编程结合使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM