首页 > 解决方案 > 你真的可以在 python 中声明变量的数据类型吗?

问题描述

我刚刚了解到,您可以使用语法“x: type”来定义您希望变量保存什么样的值。但是当我自己在 Visual Studio Code 中实际尝试时,似乎什么也没有发生。例如,如果我写:

x: int
x = 'number'
print(x)

它只是打印“数字”这个词,我没有收到任何警告。我正在使用 Python 3.9 并且没有安装任何其他版本。

标签: pythonvariablestypestype-hintingpython-typing

解决方案


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$

推荐阅读