使用用户输入启动类的新对象

Chi*_*ler 2 python oop class input python-3.x

我试图让用户输入输入新学生的详细信息,然后使用新的详细信息创建一个新的类对象,并调用 print_details 方法来显示新学生的详细信息。有人能指出我正确的方向吗?

class Student:
    def __init__(self, name, age, course, ID):
        self.name = name
        self.age = age
        self.course = course
        self.ID = ID

    def print_details(self):
        print("Name: " + self.name)
        print("Age: " + str(self.age))
        print("Course: " + self.course)
        print("Student ID: " + self.ID)

student1 = Student("Bob", 20, "Computer Science","1000121")
student2 = Student("Alice", 21, "Computer Science", "1000475")
student3 = Student("Jane", 18, "Information Technology", "1000823")
student1.print_details()
student2.print_details()
student3.print_details()
Run Code Online (Sandbox Code Playgroud)

CDJ*_*DJB 6

您可以为此使用输入

student4 = Student(input("Name:"), int(input("Age:")), input("Subject:"), input("ID:"))
student4.print_details()
Run Code Online (Sandbox Code Playgroud)

输出:

>>> Name:Bob

>>> Age:16

>>> Subject:Maths

>>> ID:1234123

Name: Bob
Age: 16
Course: Maths
Student ID: 1234123
Run Code Online (Sandbox Code Playgroud)

实现一个循环(见评论):

students = []
while True:
    if input("Type stop to stop, otherwise hit enter.") == "stop":
        break
    students.append(Student(input("Name:"), input("Age:"), input("Subject:"), input("ID:")))

for student in students:
    student.print_details()
Run Code Online (Sandbox Code Playgroud)

输出:

>>> Type stop to stop, otherwise hit enter.

>>> Name:John

>>> Age:15

>>> Subject:IT

>>> ID:3456789

>>> Type stop to stop, otherwise hit enter.

>>> Name:Mary

>>> Age:76

>>> Subject:Gardening

>>> ID:4567890

>>> Type stop to stop, otherwise hit enter.stop

Name: John
Age: 15
Course: IT
Student ID: 3456789
Name: Mary
Age: 76
Course: Gardening
Student ID: 4567890
Run Code Online (Sandbox Code Playgroud)