python错误--‘list‘ object is not callable可能的原因之一

第一、代码

功能说明:

用正则表达式匹配数字并对数字进行+1操作,然后替换原数字)

str=literal books=1000

def add1(match):
    val=match.group()
    num=int(val)+1
    return str(num)

info=re.sub(rd+,add1,str)

print info

stackoverflow中解释

“You are redefining what str() means. str is the built-in Python name of the string type, and you

dont want to change it.Use a different name for the local variable, and remove the global

statement.”

翻译

str()是系统自带的,你不能在用它的时候自己同时定义一个别的叫做str的变量,这样会冲突。

于是我把自定义的str变量改成了别的名字,str1,代码就通过了。

这是因为如果我自定义叫str的变量,str会被系统识别成字符串转换函数,这样的函数被传进sub函

数的参数里面,is not callable,也就是说,是不可调用的。

第二、举例

li = list(range(10))

print(li(0))

stackoverflow中解释 :

youve written li(m) instead of li[m].This means youre trying to call lista2 like a function, with

argument m. What you wanted to do is index lista2 like a list, with index m.

翻译

你已经写了li(m)而不是li [m]。这意味着你试图像调用函数一样调用lista2,并使用参数m。 你想

要做的是像列表一样索引lista2,索引为m。修改为li[0]就成功运行。

今天学习了 __call__函数。在Python中,函数其实是一个对象,并且所有的函数都是可调用对

象。一个类实例也可以变成一个可调用对象,只需要实现一个特殊方式__call__().

所以,当出现报错 XXX is not callable的时候,很有可能是你正在调用一个不能被调用的变量或对

象,具体表现就是你调用函数、变量的方式错误。

注意:Trace back (most recent call last)是指回溯(最近一次调用) 注意:Trace back (most recent call last)是指回溯(最近一次调用)
经验分享 程序员 微信小程序 职场和发展