Python字符串对象不可调用

时间:2012-07-12 20:27:28

标签: python string

我无法理解为什么我收到以下语句的类型错误

log.debug('vec : %s blasted : %s\n' %(str(vec), str(bitBlasted)))

type(vec)  is unicode
bitBlasted is a list

我收到以下错误

TypeError: 'str' object is not callable

2 个答案:

答案 0 :(得分:7)

隐藏内置

as Collin said,您可能会影响内置的str

>>> str = some_variable_or_string #this is wrong
>>> str(123.0) #Or this will happen
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

一种解决方案是将变量名称更改为str_或其他内容。更好的解决方案是避免使用这种匈牙利语命名系统 - 这不是Java,最大限度地使用Python的polymorphism并使用更具描述性的名称。

未定义正确的方法

另一种可能性是对象可能没有合适的__str__方法,甚至根本没有。

Python检查str方法的方法是: -

  • 班级的__str__方法
  • 其父类的__str__方法
  • 班级的__repr__方法
  • 其父类的__repr__方法
  • 以及最终后备:<module>.<classname> instance at <address>形式的字符串,其中<module>self.__class__.__module__<classname>self.__class__.__name__<address>为{ {1}}

id(self)更好的方法是使用新的__str__方法(在Python 3.x中,它们是__unicode____bytes__。然后您可以实现{ {1}}作为存根方法:

__str__

有关详细信息,请参阅this question

答案 1 :(得分:5)

正如mouad所说,你在文件中的某个位置使用了名称str。这会影响现有的内置str,并导致错误。例如:

>>> mynum = 123
>>> print str(mynum)
123
>>> str = 'abc'
>>> print str(mynum)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
相关问题