新手python类问题:AttributeError: 'list'对象没有属性

2024-06-14 19:54:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我不能让这个Python任务像我期望的那样工作。到目前为止,我得到的所有解释对我来说都没有意义。你知道吗

代码:

class attribute: #Mandatory may not be changed
    def __init__(self,Input_1,Input_2):
        self.info_1= Input_1
        self.info_2= Input_2

def Lister(List1,List2): #Mandatory Function may not be removed
    List= []
    for x in List1:
        List.append(attribute(List1,List2))
    return List


def Checker(List): #Mandatory Function may not be removed
    Awnser=input("What is"+List.info_1) 
    if Awnser != List.info_2 :
        print("Incorrect")
    else:
       print("Correct")

List_a=[1,2,3,4,5,6]
List_b=[1,2,3,4,5,6]

Checker(Lister(List_a,List_b))

该代码旨在获取List_aList_b,并询问用户另一个列表中对应的值是什么。 但是,我一直遇到这个错误,不知道为什么:

Traceback (most recent call last):
  File "so.py", line 24, in <module>
    Checker(Lister(List_a,List_b))
  File "so.py", line 14, in Checker
    Awnser=input("What is"+List.info_1) 
AttributeError: 'list' object has no attribute 'info_1'

任何帮助都将不胜感激。你知道吗


Tags: inselfinfoinputdefcheckernotattribute
1条回答
网友
1楼 · 发布于 2024-06-14 19:54:01

List属于list类型。它没有任何属性info_1。但是,List有一个attribute类型的元素。。。对象将有一个名为info_1的属性。你知道吗

我建议您使用更具描述性的变量名,尤其是避免使用现有语言概念的名称。使用类类型名List作为列表对象有点古怪;使用概念attribute作为类名完全是误导。你知道吗

我还建议您尝试增量编程:一次只实现一个小步骤。在添加更多代码之前,确保您知道如何操作它。在这里,在做任何测试之前,你已经积累了两三个新的想法,这可能会增加你的困惑。你知道吗

您当前的代码需要两个小的更改才能获得无错误的输出:

def Checker(List): #Mandatory Function may not be removed
    Awnser=input("What is"+str(List.info_1))

以及

Checker(Lister(List_a,List_b)[0])

这会将原始列表作为输出:

What is[1, 2, 3, 4, 5, 6]

相关问题 更多 >