如何在python中从用户输入添加类实例?

时间:2016-09-20 03:27:54

标签: python

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)'

我正在尝试编写成绩管理系统,所有学生的成绩都存储在他们名字的班级中。如何根据用户输入向Student类添加新实例?

    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)

我尝试过这些方法,但没有任何效果。

2 个答案:

答案 0 :(得分: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__)

答案 1 :(得分: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

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