Python属性错误类型对象没有属性

2024-05-05 12:29:59 发布

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

我正在为学校的一个项目写一些代码。我正在阅读一个列表,我已经创建了一个文本文件,有5个属性。这是我的类对象代码:

class studentclass(object):
    def __init__(self,firstname,lastname,classno,correct,mydate):
        self.firstname = firstname
        self.lastname = lastname
        self.classno = classno
        self.correct = correct
        self.mydate = mydate

在程序的后面,我将使用此代码读入数据,对其进行排序并执行一些计算:

^{pr2}$

但它不起作用。我收到以下错误消息:

AttributeError: 'list' object has no attribute 'firstname'

错误消息指向以下代码行:

firstname = myList.firstname[counter]

希望有人打电话来帮我。谢谢


Tags: 项目代码self消息列表属性object错误
2条回答

在您的代码中,您正在引用mylist.firstname。什么是mylist?这是一张单子。它有firstname属性吗?错误是告诉您它没有,并且查看代码,您没有将该属性添加到列表中。在

然而,列表中的每个元素都有这个属性。也许您是想获取列表中某个元素的firstname属性。也许是下面这些?在

for counter in range(0,totalnoofrecords):
    firstname = myList[counter].firstname
    lastname = myList[counter].lastname
    ...

在python中,当您遇到“objectx没有属性Y”这样的错误时,通常可以相信这是一个正确的语句。所以,问问你自己“为什么X没有这个属性?”。通常是a)你忘了定义这个属性,b)你拼错了属性,或者你拼错了X,或者c)X不是你认为的那样。在

你有几个问题。正如Alex S.指出的,myList是一个列表,尤其是一个包含一个元素的列表:类构造函数。
我想你想要的是:

  # assumption: you have textlines, 
  # which is an array of lines of the form firstname,lastname,blah
  myList = [studentclass(*(args.split(",")) for args in textlines]

然后执行myList[counter].firstname以获得(counter th)firstname值

相关问题 更多 >