【问题标题】:Weirdness calling str() to convert integer to string in Python 3?在 Python 3 中调用 str() 将整数转换为字符串的怪异?
【发布时间】:2011-10-27 09:46:20
【问题描述】:

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

>>> variable = str(21)

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

【问题讨论】:

  • 您是否将变量命名为“str”?
  • 您是否定义了另一个字符串变量并将其分配给变量str?因为这样做你最终会隐藏内置函数str() 例如:str = 'test'; print(str(124))
  • 投错了票。我们大多数人在学习时都使用过内置函数。看看有多少带有list = [...] 的代码示例。我更新了这个问题的标题。

标签: python python-3.x shadowing


【解决方案1】:

仅此代码不会给您带来错误。例如,我刚试过这个:

~ $ python3.2
>>> variable = str(21)
>>> variable
'21'

您在代码中的某处定义了 str = 其他内容,掩盖了 str 的内置定义。删除它,你的代码就可以正常工作了。

【讨论】:

    【解决方案2】:

    因为您可能已经通过调用自己的变量str 覆盖了str 函数。

    【讨论】:

    • 我认为你可能是对的。我关闭了我的 IDLE 会话(其中有很多我在网上找到的早期代码示例),现在我可以正确使用内置的 str 函数。那些较早的代码示例之一肯定对 BIF str() 做了一些奇怪的事情。谢谢!
    猜你喜欢
    • 2011-10-27
    • 2016-12-29
    • 2010-12-27
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 2013-02-18
    相关资源
    最近更新 更多