奇怪的是调用str()在Python 3中将整数转换为字符串?

blu*_*tic 13 python shadowing python-3.x

为什么这会给我一个错误?

>>> variable = str(21)

Traceback (most recent call last):
  File "<pyshell#101>", line 1, in <module>
    variable = str(21)
TypeError: 'str' object is not callable
Run Code Online (Sandbox Code Playgroud)

小智 38

单独的代码不会给你一个错误.例如,我刚试过这个:

~ $ python3.2
>>> variable = str(21)
>>> variable
'21'
Run Code Online (Sandbox Code Playgroud)

在你的代码中的某个地方,你要定义str =其他东西,掩盖内置的定义str.删除它,你的代码将正常工作.


Dan*_*man 13

因为您可能str通过调用自己的变量来覆盖该函数str.