我在一個類下創建了一個函式,并嘗試在讀取的 txt 檔案上呼叫該函式。更具體地說,回圈遍歷“學生物件”并在每個物件上呼叫“print_myself”方法。行迭代的輸出看起來不錯,但是當我嘗試在行迭代的輸出上呼叫該函式時,它給了我一個歸因錯誤 - 我似乎無法自己修復它。
我附上了課程和功能代碼,有人可以幫我嗎?謝謝
解決了
class Student:
def __init__(self,firstname,lastname,status,gpa):
self.firstname = firstname
self.lastname = lastname
self.status = status
self.gpa = gpa
def print_myself(self):
print("Original student information")
print("First Name:\t{}".format(self.firstname))
print("Last Name:\t{}".format(self.lastname))
print("Status:\t{}".format(self.status))
print("GPA:\t{}".format(self.gpa))
遍歷表的行并為每個資料條目創建一個學生物件,將學生物件存盤在“學生”串列中。
原來的
import pandas as pd
students = []
data = pd.read_csv('students.txt')
df = pd.DataFrame(data)
for index, row in df.iterrows():
students.append({'firstname':row['firstname'],
'lastname':row['lastname'],
'status':row['status'],
'gpa':row['gpa']})
print(students)
Student.print_myself(student)
固定的
students = []
data = pd.read_csv('students.txt')
df = pd.DataFrame(data)
print( df)
for index, row in df.iterrows():
students.append(Student(**{'firstname':row['firstname'],
'lastname':row['lastname'],
'status':row['status'],
'gpa':row['gpa']}))
for i in range (0,10):
students[i].print_myself()
列印輸出(學生)
Original student information
First Name: Mike
Last Name: Barnes
Status: freshman
GPA: 4.0
Original student information
First Name: Jim
Last Name: Nickerson
Status: sophomore
GPA: 3.0
Original student information,....
uj5u.com熱心網友回復:
我看到兩個問題:print_myself是一個實體方法,所以你需要一個類的實體,比如Student().
也就是說,而不是:
Student.print_myself(student)
我建議:
students[0].print_myself()
第二個是當添加到學生時,在行中students.append,您附加了一個dict物件,但應首先將其轉換為Student物件。
例如,這一行:
students.append({'firstname':row['firstname'],
'lastname':row['lastname'],
'status':row['status'],
'gpa':row['gpa']})
我建議像這樣嘗試:
students.append(Student(**row))
或者,為了更安全:
students.append(Student(**{'firstname':row['firstname'],
'lastname':row['lastname'],
'status':row['status'],
'gpa':row['gpa']}))
uj5u.com熱心網友回復:
您尚未實體化 Student 類的新物件
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/352459.html
上一篇:組/樞軸字典Python
