[英]Python string object not callable
我無法理解為什么我得到以下語句的類型錯誤
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
無論是Collin說的 ,你都可以隱藏內置的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的多態 ,並使用更具描述性的名稱。
另一種可能性是對象可能沒有合適的__str__
方法,甚至根本沒有。
Python檢查str
方法的方法是: -
__str__
方法 __str__
方法 __repr__
方法 __repr__
方法 <module>.<classname> instance at <address>
,其中<module>
是self.__class__.__module__
, <classname>
是self.__class__.__name__
, <address>
是id(self)
甚至比__str__
更好的是使用新的__unicode__
方法(在Python 3.x中,它們是__bytes__
和__str__
。然后你可以將__str__
實現為存根方法:
class foo:
...
def __str__(self):
return unicode(self).encode('utf-8')
有關詳細信息,請參閱此問題 。
正如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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.