将类追加到列表会导致追加str error python

将类追加到列表会导致追加str error python,python,append,Python,Append,所以我的程序有一个名为persons的类。我试图让程序从输入文件中读取它,然后读取它并将其排列到类中。当我试着给全班同学一个列表的时候。它给了我这个错误: AttributeError:“str”对象没有属性“append” 我以前也用过这段代码做过类似的事情,但没有从文件中读取。我想知道是什么导致了这个错误。 这是我的密码: class person: def __init__(self, FName, FLast,age ): self.FName=FName self.FL

所以我的程序有一个名为persons的类。我试图让程序从输入文件中读取它,然后读取它并将其排列到类中。当我试着给全班同学一个列表的时候。它给了我这个错误: AttributeError:“str”对象没有属性“append” 我以前也用过这段代码做过类似的事情,但没有从文件中读取。我想知道是什么导致了这个错误。 这是我的密码:

class person:
def __init__(self, FName, FLast,age ):
    self.FName=FName
    self.FLast=FLast
    self.age=age


from sys import argv

script = argv
filename = raw_input('enter filename: ')
txt = open(filename, 'r+')
count = 0


i = 2
lines = txt.readlines()
z=lines[0]
a=lines[1]
r=lines[2]
hi=person(z,a,r)
a=[hi]

while i != -1:
  try:
    z=lines[i]
    a=lines[i+1]
    r=lines[i+2]
    i = i + 3
    hi=person(z,a,r)
    a.append[hi]
except IndexError:
    i = -1

代码中的几个问题-

  • a.append[hi]
    -这不是追加的方式,append是一个函数,您必须调用它,并将要追加的值作为参数传递给它

  • 您将
    a
    定义为行中的字符串-
    a=lines[i+1]
    ,然后尝试附加到它

  • 您可能希望在
    之外创建一个新列表,而
    ,然后继续附加到该列表

    范例-

    classlist = []
    while i != -1:
      try:
        z=lines[i]
        a=lines[i+1]
        r=lines[i+2]
        i = i + 3
        hi=person(z,a,r)
        classlist.append(hi)
    except IndexError:
        i = -1
    

    这是因为您只从列表中获取一个元素。然后列表将返回该元素的原始类型

    class person:
        def __init__(self, FName, FLast,age ):
            self.FName=FName
            self.FLast=FLast
            self.age=age
    
    
    from sys import argv
    
    script = argv
    filename = raw_input('enter filename: ')
    txt = open(filename, 'r+')
    count = 0
    
    
    i = 2
    lines = txt.readlines()
    z=lines[0]
    a=lines[1]
    r=lines[2]
    hi=person(z,a,r)
    a=[hi]
    
    while i != -1:
        try:
            z=lines[i]
            a=list(lines[i+1]) #converting it to list
            r=lines[i+2]
            i = i + 3
            hi=person(z,a,r)
            a.append(hi) #append is a method so ()
        except IndexError:
            i = -1
    

    append()
    not
    append[]
    文件看起来像这样:第一行:名字,第二行:第二个名字,第三行:年龄,我一共有三个这样的人,所以整个文件有9行长