Python列表报错解决方案:’NoneType’ object has no attribute ‘XXX’

在学习python列表时,遇到了以下问题:

AttributeError: 'NoneType' object has no attribute 'XXX'

s1 = input()
L1 = [s1]

L2 = [‘a’,‘b’,‘c’]
L1 = L1.append(L2)

print(L1)
print(L2.reverse())

具体报错输出如下:

AttributeError: 'NoneType' object has no attribute 'append' 
None

解决方法: 

#改
L1 = L1.append(L2)
print(L2.reverse())

#为
L1.append(L2)
L2.reverse()
print(L2)

原因是:

append() 函数没有返回值,即 L.append(object)  –> None

所以不能再赋值回去

同理,L.reverse() –> None

调试查看:

调用append() 函数返回 None,如下:

>>> x = [1, 2, 3]
>>> y = x.append(4)
>>> y is None
True
>>> x
[1, 2, 3, 4]
物联沃分享整理
物联沃-IOTWORD物联网 » Python列表报错解决方案:’NoneType’ object has no attribute ‘XXX’

发表评论