该错误TypeError: ‘str’ object is not callable字面上意思:
就是str不可以被系统调用,其实原因就是:你正在调用一个不能被调用的变量或对象,具体表现就是你调用函数、变量的方式错误
所以,这个错误想表达的就是:str()是系统自带的,你不能在用它的时候自己同时定义一个别的叫做str的变量,这样会冲突.
出现这个情况错误一般是:
1.str变量重复定义
2.变量重复定义
3.函数或者字符串调用错误
例子1:str字符串重复定义
classmate = ['one', 'two', 'three']
for str in classmate:
print(s + ', ')
print('\n')
str() 是一个builtin 函数,在这里将一个普通变量定义为str,编译器在之后的解释执行过程中,会一直把str作为一个普通变量处理,自然在希望调用str()的时候会出问题。
把这里的 str 改成 s 等其他变量,就能解决问题。
例子2:变量名重复定义
class Book:
def __init__(self, price, color):
self.price = price
self.color = color # color发生冲突,导致出错
def color(self):
print('书的颜色是:%s'%self.color)
eng = Book(10, 100, 'red')
print('书的价格是:%d'%eng.price)
eng.color()
Traceback (most recent call last):
File “/home/albert/PycharmProjects/xi.py”, line 14, in
eng.color()
TypeError: ‘str’ object is not callable
书的价格是:100
所以,不能同时定义同一个名字叫color的,会冲突.改成color1即可!
例子三:函数或者字符串调用错误
def get_list_urls(self):
for list in self.domainList:
#print(self.domainList[list])
url = self.domainList[list]
reqs = requests.get(url = url, headers = self.headers)
html = reqs.text()
bfHtml = BeautifulSoup(html)
上例子也会报:‘str’ object is not callable
其原因是:requests的返回值reqs并没有text()方法,BeautifulSoup接收一个字符串,而我们误将 reqs.text 写成了 reqs.text(),就造成了这个错误。