繁体   English   中英

AttributeError:'NoneType'对象在edX上的Python中没有属性'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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM