【发布时间】:2020-08-07 05:22:56
【问题描述】:
Int 在 python 中不是关键字,因此可以用作变量名。 我尝试为名称分配一个字符串,它起作用了。
我是在 Python3.8.2 的 IDLE 中做的
>>> a = int(4.5)
>>> print(a)
4
>>> int = 'abc'
>>> print(int)
abc
>>> b = int(5.7)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
b = int(5.7)
TypeError: 'str' object is not callable
>>> print(b)
代码在没有最后一部分的情况下工作。 即来自 b = int(5.7)
为什么会这样? int 不应该是关键字吗? 我们如何修复它,保持现有代码完好无损,就像在控制台中工作一样?
我尝试使用 del 关键字,它成功了。但我不知道为什么。
>>> del int
>>> b = int(5.7)
>>> print(b)
5
这行得通。
请解释一下。 :)
【问题讨论】:
-
好像有些名字不是关键字。 int 和 str 是两个例子。
-
因为
int只是一个变量,它指的是内置类int。就像如果你做class Foo: pass,那么你可以做Foo = 'a string'。类、函数等与 Python 中的任何其他对象一样是一流的对象
标签: python python-3.x class variables int