TypeError:'str'对象不可调用(Python)


76

码:

import urllib2 as u
import os as o
inn = 'dword.txt'
w = open(inn)
z = w.readline()
b = w.readline()
c = w.readline()
x = w.readline()
m = w.readline()
def Dict(Let, Mod):
    global str
    inn = 'dword.txt'
    den = 'definitions.txt'

    print 'reading definitions...'

    dell =open(den, 'w')

    print 'getting source code...'
    f = u.urlopen('http://dictionary.reference.com/browse/' + Let)
    a = f.read(800)

    print 'writing source code to file...'
    f = open("dic1.txt", "w")
    f.write(a)
    f.close()

    j = open('defs.txt', 'w')

    print 'finding definition is source code'
    for line in open("dic1.txt"):
        if '<meta name="description" content=' in line:
           j.write(line)

    j.close()

    te = open('defs.txt', 'r').read().split()
    sto = open('remove.txt', 'r').read().split()

    print 'skimming down the definition...'
    mar = []
    for t in te:
        if t.lower() in sto:
            mar.append('')
        else: 
            mar.append(t)
    print mar
    str = str(mar)
    str = ''.join([ c for c in str if c not in (",", "'", '[', ']', '')])

    defin = open(den, Mod)
    defin.write(str)
    defin.write('                 ')
    defin.close()

    print 'cleaning up...'
    o.system('del dic1.txt')
    o.system('del defs.txt')
Dict(z, 'w')
Dict(b, 'a')
Dict(c, 'a')
Dict(x, 'a')
Dict(m, 'a')
print 'all of the definitions are in definitions.txt'

第一次Dict(z, 'w')工作,然后第二次出现错误:

Traceback (most recent call last):
  File "C:\Users\test.py", line 64, in <module>
    Dict(b, 'a')
  File "C:\Users\test.py", line 52, in Dict
    str = str(mar)
TypeError: 'str' object is not callable

有人知道为什么是这样吗?

@格雷格·休吉尔:

我已经尝试过了,但出现错误:

Traceback (most recent call last):
 File "C:\Users\test.py", line 63, in <module>
    Dict(z, 'w')
  File "C:\Users\test.py", line 53, in Dict
   strr = ''.join([ c for c in str if c not in (",", "'", '[', ']', '')])
TypeError: 'type' object is not iterable

6
重命名str变量的所有实例,包括该错误抱怨的第53行中的实例。
亚当·罗森菲尔德

Answers:


128

这就是问题:

global str

str = str(mar)

您正在重新定义什么str()意思。str是字符串类型的内置Python名称,您不想更改它。

为本地变量使用其他名称,然后删除该global语句。


7
并非要使用,而是可以使用的str()功能__builtins__.str()。当然,在99.9999%的情况下使用它当然是一个坏主意。
n611x007 2013年

2
请记住,您需要重新启动python内核才能str()返回功能。
yeliabsalohcin

5
@yeliabsalohcin,del str即使您不小心覆盖了它,也可以恢复其内置功能。
wovano

118

虽然不在您的代码中,但另一个难以发现的错误是当%尝试格式化字符串时缺少字符时:

"foo %s bar %s coffee"("blah","asdf")

但应该是:

"foo %s bar %s coffee"%("blah","asdf")

丢失%将导致相同的结果TypeError: 'str' object is not callable


6
谢谢你,先生!简单的错误,但极大地破坏了脚本。
ChrisR 2014年

我知道这确实很老,但是我遇到了这个问题,这个答案有所帮助,谢谢@naxa
Bbit 2015年

经过一个小时的故障排除,这才救了我。谢谢!
迈克尔

谢谢,这是导致我的情况相同错误的原因。
saran3h

具有相同名称的属性和方法,使用字符串覆盖该方法,然后尝试执行该方法/字符串,这也导致TypeError:'str'对象不可调用
Puggan Se

26

在我的情况下,我有一个类,该类具有一个方法和一个同名的字符串属性,我试图调用该方法,但正在获取字符串属性。


谢谢-调试一些代码,并且合法方法带有 @property批注,我没有注意到,您的回答帮助我看到了它。
jgreve

记录阴影可能很好,并且在发生这种情况时,诸如严格模式之类的东西会导致某种RuntimeWarning,但是 按照规范将属性替换为方法,反之亦然是完全有效的python
ThorSummoner

18

如果您有变量str并尝试调用str()函数,则会出现此错误。


感谢您使用“普通英语”的回答,对于此python n00b确实有用;-)
Pim Hazebroek

16

请务必注意(如果您是Google来的,则要注意)“ TypeError:'str'对象不可调用”意味着仅尝试将先前声明为String-type的变量用作函数(例如,最后添加括号。)

如果您使用任何其他内置方法作为变量名称,则也可以获得完全相同的错误消息。


8

这种情况的另一种情况:处理__repr__对象的功能,其中format()调用非透明地失败。

在我们的示例中,我们在上使用了一个@property装饰器,__repr__并将该对象传递给format()。所述@property装饰使得__repr__对象被打开成一个字符串,然后在结果str对象不是可调用错误。


1
谢谢,这也是我的问题(我没有使用format,但是由于某种原因,在@property上有一个__repr__
贾斯汀

哦,就是这样!我不小心遇到@property__str__()
sba

6

每当发生这种情况时,只需发出以下命令(它也已发布在上面)

>>> del str

那应该解决它。


5

检查您的输入参数,并确保没有一个名为的参数type。如果是这样,那么您将发生冲突并得到此错误。


3
str = 'Hello World String'    
print(str(10)+' Good day!!')

甚至我上面的代码都遇到了问题,因为我们正在隐藏str()函数。

解决方法是:

string1 = 'Hello World String'
print(str(10)+' Good day!!')

2

我刚遇到的一个问题是不小心调用了字符串

"Foo" ("Bar" if bar else "Baz")

您可以像这样将字符串彼此并置,以串联字符串

"Foo" "Bar"

但是由于第一个示例中的括号大,它以为我正在尝试调用 "Foo"


2

也可能是您尝试以错误的方式建立索引:

a = 'apple'
a(3) ===> 'str' object is not callable

a[3] = l

2

我又遇到了同样的错误!

原来我已经在模型上创建了一个属性,但是愚蠢地用括号将该属性调用。

希望这对某人有帮助!


而且,如果您对该属性使用setter方法并使用括号对其进行调用,则也更容易理解。
Lokal_Profil

2

我有同样的错误。在我的情况下,因为一个名为str的变量而没有。但是因为我用一个str参数和一个变量命名了一个函数。

same_name = same_name( var_name: str)

我循环运行。第一次运行正常。我第二次收到此错误。将变量重命名为与函数名称不同的名称可以解决此问题。因此,我认为这是因为Python曾经在范围内关联了一个函数名,第二次尝试将左侧部分(same_name =)关联为对该函数的调用,并检测到str参数不存在,因此该参数丢失了,然后抛出该错误。


0

我从不完整的方法检查中收到此警告:

if hasattr(w, 'to_json'):
    return w.to_json()
             ######### warning, 'str' object is not callable

它假定w.to_json是一个字符串。解决方案是添加callable()检查:

if hasattr(w, 'to_json') and callable(w.to_json):

然后警告消失了。


0

建议不要使用str int listetc ..作为变量名,即使python允许。这是因为尝试访问名称相同的保留关键字时可能会造成此类事故


-1

就我而言,我有一个带有方法的类。该方法没有“ self”作为第一个参数,并且在我对该方法进行调用时抛出了错误。一旦将“ self”添加到方法的参数列表中,就可以了。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.