![](/img/trans.png)
[英]Python : AttributeError: 'NoneType' object has no attribute 'append'
[英]AttributeError: 'NoneType' object has no attribute 'append' in Python on edX
def adding_report(report = [445, 234]):
at = input("Choose a report type: 'A' or 'T'")
while at.lower() == 'a' or 't' == False:
at = input("Choose a report type: 'A' or 'T' : ")
while True:
re = input("print an integer or 'Q' : ")
if re.isdigit() == True:
report = report.append(re)
elif re.startswith('q') == True:
if at.lower() == 'a' is True:
print(report)
print(sum(report))
break
elif at.lower() == 't' is True:
print(sum(report))
break
else:
pass
elif re.isdigit() == False and re.lower().startswith('q'):
print('invalid response.')
adding_report(report = [])
我正在使用此代碼嘗試獲取添加的報告,但出現錯誤AttributeError:'NoneType'對象沒有屬性'append'。 請幫忙。
在這個片段中
if re.isdigit() == True:
report = report.append(re)
您只需要report.append(re)
,而不是report = report.append(re)
。 通過將report.append(re)
分配給report
您將覆蓋列表而沒有任何內容,因為append()沒有返回值。 因此, report
變量的類型為NoneType
。
當您追加列表時,它返回None。 見下文
>>> A = [1, 2, 3]
>>> print(A.append(4))
None
>>> print(A)
[1, 2, 3, 4]
>>> A = A.append(5)
>>> print(A)
None
因此,當您更新列表時,請確保只執行report.append(re)
而不是report = report.append(re)
問題在這里:
report = report.append(re)
report.append(re)
實際上返回None
。 因此,這意味着您要python將已經存在的list
對象( report
)轉換為NoneType
。 因此,它不再是list
並且您無法進一步添加任何內容。 您想要做的是report.append(re)
。 這將簡單地將re
附加到現有列表report
而無需將其重新分配給NoneType
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.