在变量声明中使用冒号 [英] Use of colon in variable declaration

查看:61
本文介绍了在变量声明中使用冒号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近有人问我这在 python 中意味着什么:

<代码>>>>字符:str

我不知道.我以前从未见过.我检查了文档,没有类似的东西.一个人的建议是它是静态类型声明,但文档中也绝对没有关于它的内容.

有了上面的,如果我<代码>>>>type(char) 失败

如果我<代码>>>>char : str = 'abc' 就可以了,type(char) 的结果是.但是它不能是静态声明,因为我可以 >>>>>char : str = 4 并且 type(char) 变成 .

所以我来这里是为了收集众多SO霸主的智慧.这是什么意思?

解决方案

您正在查看变量的注释.提示移动到 __annotations__ 映射:

<预><代码>>>>字符:str>>>__注释__{'char':}

变量注解用于支持第三方工具,例如类型检查器;语法是 Python 3.6 中的新语法.

请参阅PEP 526 -- 变量注释的语法Python 3.6 中的新功能:

<块引用>

就像函数注解一样,Python 解释器没有给变量注解附加任何特定的含义,只将它们存储在类或模块的 __annotations__ 属性中.

I was asked recently what this means in python:

>>> char : str

I had no idea. I'd never seen that before. I checked the docs and there isn't anything like that. One person's suggestion was that it is static type declaration, but there is absolutely nothing in the docs about that either.

With the above, if I >>> type(char) it fails

If I >>> char : str = 'abc' it works, and the results of type(char) is <class: str>. It can't be static declaration though, because I can >>> char : str = 4 and type(char) becomes <class: int>.

So I come here to collect the wisdom of the many SO overlords. What does that mean?

解决方案

You are looking at an annotation for a variable. The hint is moved to the __annotations__ mapping:

>>> char: str
>>> __annotations__
{'char': <class 'str'>}

Variable annotations are there to support third-party tooling, such as type checkers; the syntax is new in Python 3.6.

See PEP 526 -- Syntax for Variable Annotations, and What's new in Python 3.6:

Just as for function annotations, the Python interpreter does not attach any particular meaning to variable annotations and only stores them in the __annotations__ attribute of a class or module.

这篇关于在变量声明中使用冒号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆