我开始玩python一点点,作为一个新手,我尝试了这个:
>>> s="";str=""
>>> for x in [ 1,2,3,4,5,6 ] :
... s += str(x)
...
Traceback (most recent call last):
File "<console>", line 3, in <module>
TypeError: 'str' object is not callable
我意外地声明了一个名为str
的变量(str应该是一个函数)。
str
并确保这不会发生或使其变得困难?答案 0 :(得分:1)
根据您的问题,您已经定义了
str=""因此,当您调用将值转换为字符串的str方法时,它将不会调用实际方法来代替它将调用
str=""
。
这就是为什么你得到错误,因为你不能调用str对象将int转换为string。
答案 1 :(得分:1)
这是import <module>
而不是from <module> import *
的用途。只要在<module>
中使用str唯一含义的局部变量值,就可以使用
module.str
elswhere,没有名称空间。
唯一无法发生冲突的令牌是keywords。这是预期的功能,无法阻止这种情况:everything is an object in Python
您可能想要使用一些IDE工具,p.ex。 Eclipse + PyDev,它检查您的代码并警告可能的错误。