簡體   English   中英

Python字符串對象不可調用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM