关于 xxx object is not callable

def experiment(num):
    num_list = []
    for i in range(int(num)):
        num_list.append(i)
    return(num_list)

alist = ['2','3']
for number in alist:
    for experiment in experiment(number):
        print(experiment)
0
1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in ()
 7 alist = ['2','3']  8 for number in alist: ----> 9 for experiment in experiment(number):  10 print(experiment) TypeError: 'int' object is not callable

is not callable,是指不能执行。例如变量后面加()就会报这个错误。在for循环中,容易报这个错误。
例如在上面的例子中,for循环中使用的变量名称experiment和函数experiment(num)有一样的名称。
在第一次循环时,变量experiment还未被赋值,所以函数experiment(num)可以正常执行。
但第二次循环时,变量experiment已经被赋值成为一个int,所以函数experiment(num)无法正常执行,并报 'int' object is not callable。

修改方法:
避免变量名和函数名一样。修改如下:
def experiment(num):
    num_list = []
    for i in range(int(num)):
        num_list.append(i)
    return(num_list)

alist = ['2','3']
for number in alist:
    for experiment_ in experiment(number):
        print(experiment_)
0
1
0
1
2
 


转载于:https://www.cnblogs.com/levylaw/p/10113656.html

你可能感兴趣的:(关于 xxx object is not callable)