python - 你真的可以在 python 中声明变量的数据类型吗?
问题描述
我刚刚了解到,您可以使用语法“x: type”来定义您希望变量保存什么样的值。但是当我自己在 Visual Studio Code 中实际尝试时,似乎什么也没有发生。例如,如果我写:
x: int
x = 'number'
print(x)
它只是打印“数字”这个词,我没有收到任何警告。我正在使用 Python 3.9 并且没有安装任何其他版本。
解决方案
python 中的类型不会在运行时进行测试,您需要通过http://mypy-lang.org “在编译时”之类的方式来验证它们,如下所示:
(venv) rasjani@MacBook-Pro ~/src/test$ cat test.py
x: int
x = 'number'
print(x)
(venv) rasjani@MacBook-Pro ~/src/test$ mypy test.py
test.py:2: error: Incompatible types in assignment (expression has type "str", variable has type "int")
Found 1 error in 1 file (checked 1 source file)
(venv) rasjani@MacBook-Pro ~/src/test$
推荐阅读
- python - pyhamcrest - 比较两个列表
- graphql - 如何在其他文件中使用graphql类型进行关系而不重复
- qt - QML:原始模型中的动态视图重新排序
- android - Xamarin UITest ScrollDownTo for Android 真的很慢
- javascript - 如何在 CSS 规则中选择具有 Windows 格式路径的属性?
- node.js - 如何使用 Node.js 和 Axios 将文件上传到 AWS 中的预签名 URL?
- mysql - 如何在 Mariadb 的 regexp_replace 中使用正则表达式标志?
- javascript - 如何从firestore数据库返回值?
- c++ - 静态成员声明为 const 但初始化为 constexpr
- arrays - 带有姓名、姓氏等的 Java 数组