Python raw_input到类中声明的字典中

时间:2009-12-05 18:59:32

标签: python variables dictionary class

我对Python非常陌生,我真的需要能够解决这个问题。我想通过raw_input向用户询问模块和等级是什么,然后将其放入已在Student类中定义的字典作为等级。我不知道该怎么做!提前谢谢!

students = [] # List containing all student objects (the database)

def printMenu(): 
    print "------Main Menu------\n" "1. Add a student\n" "2. Print all students\n" "3. Remove a student\n" "---------------------\n"


class Student:
    firstName = ""
    lastName = ""
    age = 0
    studentID = ""
    degree = ""
    grades = {"Module Name":"","Grade":""}

    def setFirstName(self, firstName):
        self.firstName = firstName

    def getFirstName(self):
        return self.firstName

    def setLastName(self, lastName):
        self.lastName = lastName

    def getLastName(self):
        return self.lastName

    def setDegree(self,degree):
        self.degree = degree

    def getDegree(self):
        return self.degree

    def setGrades(self, grades):
        self.grades = grades

    def getGrades(self):
        return self.grades

    def setStudentID(self, studentid):
        self.studentid = studentid

    def getStudentID(self):
        return self.studentid

    def setAge(self, age):
        self.age = age

    def getAge(self):
        return self.age


def addStudent():
        count = 0
        firstName = raw_input("Please enter the student's first name: ")
        lastName = raw_input("Please enter the student's last name: ")
        degree = raw_input("Please enter the student's degree: ")
        while count != -1:
            student.grades = raw_input("Please enter the student's module name: ")
            #student.grades["Grade"] = raw_input("Please enter the grade for %: " % grades)

        studentid = raw_input("Please enter the student's ID: ")
        age = raw_input("Please enter the student's age: ")        

        student = Student() # Create a new student object
        student.setFirstName(firstName) # Set this student's first name
        student.setLastName(lastName)
        student.setDegree(degree)
        student.setGrades(grades)
        student.setStudentID(studentid)
        student.setAge(age)

        students.append(student) # Add this student to the database

1 个答案:

答案 0 :(得分:2)

一些事情:

  1. 将类属性的初始化移至__init__方法:

  2. 杰弗里说,摆脱所有的吸气者和制定者。

  3. 使用具有模块名称作为键的dict并将等级作为值:

  4. 一些代码段:

    def __init__(self, firstName, lastName, age, studentID, degree):
        self.firstName = firstName
        self.lastName = lastName
        ...
        self.grades = {}
    

        while True:
            module_name = raw_input("Please enter the student's module name: ")
            if not module_name:
                break
            grade = raw_input("Please enter the grade for %s: " % module_name)
            student.grades[module_name] = grade