2016-09-20 51 views
0
class Student(object): 
    def __init__(self, name, chinese = 0, math = 0, english = 0): 
     self.name = name 
     self.chinese = chinese 
     self.math = math 
     self.english = english 
     self.total = self.chinese + self.math + self.english 
     Student.list.append(name)' 

我想寫一個成績管理系統,所有的學生的成績都存儲在他們的名字的類。如何根據用戶輸入將新實例添加到班學生?如何從python中的用戶輸入添加一個類實例?

name = raw_input("Please input the student's name:") 
    chinese = input("Please input Chinese score:") 
    math = input("Please input Math score:") 
    english = input("Please input English score:") 
    name = Student(name, chinese, math, english) 
    # eval(name) 
    # name = Student(name, chinese, math, english) 

我試過用這些方法,但沒有任何結果。

+1

什麼是'new_student'? – Li357

+0

最後兩行代碼沒什麼意義,問題本身 - 「添加新實例」到哪裏?另外,你爲什麼要將你的註釋代碼作爲問題的一部分發布? –

+1

*什麼*不起作用? –

回答

0
import pprint 
class Student(): 
#blah blah blah 

if __name__ == "__main__": 
    list_of_students = [] 
    while True: 
     if raw_input("Add student? (y/n)") == "n": 
      break 
     # ask your questions here 
     list_of_students.append(Student(# student data)) 
    for student in list_of_students: 
     pprint.pprint(student.__dict__) 
+0

sutudent ???順便說一句,在追加新學生之前,我會檢查用戶輸入是否等於「y」。 –

+0

meh,preferences ...取決於你是否習慣於編寫早期退貨或單一退貨功能...如果用戶剛剛進入,因爲他們有100名學生進入我的方式可能是首選...但是,偏好和用例 – pyInTheSky

+0

也是一個sutudent就像一個yute:P – pyInTheSky

0

請嘗試以下方法。 :

from collections import defaultdict 
class Student: 

    def __init__(self, name=None, chinese=None, math=None, english=None): 
     self.student_info = defaultdict(list) 
     if name is not None: 
      self.student_info['name'].append(name) 
      self.student_info['chinese'].append(chinese) 
      self.student_info['math'].append(math) 
      self.student_info['english'].append(english) 

    def add_student(self, name, chinese, math, english): 
     if name is not None: 
      self.student_info['name'].append(name) 
      self.student_info['chinese'].append(chinese) 
      self.student_info['math'].append(math) 
      self.student_info['english'].append(english) 
     return None 

在你原來的問題代碼中,沒有添加方法(只有一個構造函數)。因此,您不能將任何新學生的信息添加到對象。

相關問題