簡體   English   中英

Python屬性錯誤-類型對象沒有屬性

[英]Python Attribute Error - Type Object has no Attribute

我在學校為一個項目寫一些代碼。 我正在閱讀一個列表,該列表已創建為具有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:“列表”對象沒有屬性“名字”

錯誤消息指向代碼的這一行:

名字= myList.firstname [計數器]

希望有人打電話幫助我。 謝謝

在您的代碼中,您引用的是mylist.firstname 什么是我的mylist 這是一個清單。 它具有firstname屬性嗎? 錯誤是告訴您它沒有,並且您沒有在代碼中將該屬性添加到列表中。

但是,列表的每個元素都具有該屬性。 也許您打算獲取列表元素之一的firstname屬性。 也許以下,也許?

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

在python中,當出現諸如“對象X沒有屬性Y”之類的錯誤時,通常可以將其視為真實語句。 因此,問自己“為什么X不具有該屬性?”。 通常是a)忘記定義該屬性,b)拼寫錯誤的屬性或X拼寫錯誤,或者c)X不是您認為的那樣。

你有幾個問題。 正如Alex S.指出的那樣,您的myList是一個List,特別是一個包含一個元素的列表:類構造函數。
我認為您想要的是這樣的:

  # 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以獲取(第myList[counter].firstname個)firstname值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM