Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/maven/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python属性错误-类型对象没有属性_Python_Python 3.x - Fatal编程技术网

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

Python属性错误-类型对象没有属性,python,python-3.x,Python,Python 3.x,我正在为学校的一个项目写代码。我正在阅读一个列表,该列表是我创建的一个具有5个属性的文本文件。这是我的类对象代码: class studentclass(object): def __init__(self,firstname,lastname,classno,correct,mydate): self.firstname = firstname self.lastname = lastname self.classno = classno

我正在为学校的一个项目写代码。我正在阅读一个列表,该列表是我创建的一个具有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
稍后在程序中,我将使用此代码读取数据,对其进行排序并执行一些计算:

myList = [studentclass]
totalnoofrecords = 0
counter = 0

for counter in range(0,totalnoofrecords):
    firstname = myList.firstname[counter]
    lastname = myList.lastname[counter]
    classno = myList.classno[counter]
    correct = myList.correct[counter]
    mydate = myList.mydate[counter]
    newname = myList.firstname[counter +1]
    if newname == firstname:
            grade = grade + studentclass.correct(counter +1)
            nummberofattempts = 2
    newname2 = studentclass.firstname(counter +2)
    if newname2 == firstname:
            grade = grade + studentclass.correct(counter +2)
            nummberofattempts = 3
    mean = grade / numberofattempts

    print ("num ",counter ,"=", myList[counter])
但它不起作用。我收到以下错误消息:

AttributeError:“list”对象没有属性“firstname”

错误消息指向此代码行:

firstname=myList.firstname[计数器]


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

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

但是,列表中的每个元素都有该属性。也许您想获取列表中某个元素的
firstname
属性。也许是下面的,也许

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

在python中,当您得到一个类似“objectx没有属性Y”的错误时,您通常可以相信这是一个true语句。所以,问问你自己“为什么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值

您的
myList
是一个列表,而不是类实例。列表没有属性。答案很好,除了你应该直接在我的列表上迭代,而不是在一个范围内。