您真的可以在 python 中声明变量的数据类型吗?

Can you actually declare the data type for a variable in python?

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

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

它只打印 'number' 这个词,我没有收到任何关于它的警告。我正在使用 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$