我无法理解为什么我收到以下语句的类型错误
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
遮蔽内置
Either 正如科林所说 https://stackoverflow.com/a/11460162/296974,你可能会隐藏内置的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 的多态性 http://en.wikipedia.org/wiki/Polymorphism_(computer_science)充分发挥作用,并使用更具描述性的名称。
没有定义正确的方法
另一种可能性是该对象可能没有适当的__str__
方法,甚至根本不是一种方法。
Python 检查的方式str
方法是:-
- the
__str__
类的方法
- the
__str__
其父类的方法
- the
__repr__
类的方法
- the
__repr__
其父类的方法
- 最后的后备:一个字符串形式
<module>.<classname> instance at <address>
where <module>
is self.__class__.__module__
, <classname>
is self.__class__.__name__
and <address>
is id(self)
甚至比__str__
将使用新的__unicode__
方法(在 Python 3.x 中,它们是__bytes__
and __str__
。然后你可以实施__str__
作为存根方法:
class foo:
...
def __str__(self):
return unicode(self).encode('utf-8')
See 这个问题 https://stackoverflow.com/questions/1307014/python-str-versus-unicode更多细节。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)