Python 中 AttributeError: ‘int’ object has no attribute ‘append’ 错误

当我们对整数调用 append() 方法时,会出现 Python“AttributeError: ‘int’ object has no attribute ‘append’ ”。 要解决该错误,需要确保我们调用 append 的值是列表类型。

下面是产生上述错误的示例代码

my_list = ['a', 'b', 'c']

# 👇️ reassign variable to integer
my_list = 10

print(type(my_list))  # 👉️ <class 'int'>

# ⛔️ AttributeError: 'int' object has no attribute 'append'
my_list.append('d')

我们将 my_list 变量重新分配给一个整数,并尝试对导致错误的整数调用 append() 方法。

如果我们 print() 调用 append() 的值,它将是一个整数。

要解决该错误,我们需要查明在代码中将值设置为整数的确切位置并更正分配。

要解决示例中的错误,我们必须删除重新分配或更正它。

my_list = ['a', 'b', 'c']

my_list.append('d')

print(my_list) # 👉️ ['a', 'b', 'c', 'd']

append() 方法将一个项目添加到列表的末尾。

对整数调用该方法会导致错误。

确保我们在调用追加时没有尝试访问特定索引处的列表。

fav_numbers = [1, 2, 3]

# ⛔️ AttributeError: 'int' object has no attribute 'append'
fav_numbers[0].append(4)

print(fav_numbers)

fav_numbers 变量存储一个数字列表。

我们访问了索引 0(即整数 1)处的列表项,并对导致错误的结果调用了 append() 方法。

要解决这种情况下的错误,需要删除索引访问器并调用列表上的 append() 方法。

fav_numbers = [1, 2, 3]

fav_numbers.append(4)

print(fav_numbers)  # 👉️ [1, 2, 3, 4]

我们还可以将调用返回整数的函数的结果分配给变量。

def get_list():
    return 100


my_list = get_list()

# ⛔️ AttributeError: 'int' object has no attribute 'append'
my_list.append('d')

my_list 变量被分配给调用 get_list 函数的结果。

该函数返回一个整数,因此我们无法对其调用 append()

要解决该错误,我们必须找到为特定变量分配整数而不是列表的位置并更正分配。


总结

当我们对整数调用 append() 方法时,会出现 Python“AttributeError: ‘int’ object has no attribute ‘append’”。 要解决该错误,请确保我们调用 append 的值是列表类型。