【问题标题】:Can you actually declare the data type for a variable in python?你真的可以在 python 中声明变量的数据类型吗?
【发布时间】:2021-11-14 01:12:47
【问题描述】:
我刚刚了解到,您可以使用语法“x: type”来定义希望变量保存的值类型。但是当我自己在 Visual Studio Code 中实际尝试时,似乎什么也没有发生。例如,如果我写:
x: int
x = 'number'
print(x)
它只是打印“数字”这个词,我没有收到任何警告。我使用的是 Python 3.9,没有安装任何其他版本。
【问题讨论】:
标签:
python
variables
types
type-hinting
python-typing
【解决方案1】:
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$