2016-09-20 48 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 

在你原来的问题代码中,没有添加方法(只有一个构造函数)。因此,您不能将任何新学生的信息添加到对象。

相关问题