gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:16:58 27 4
gpt4 key购买 nike

我正在尝试获取用户输入以输入新学生的详细信息,然后使用新的详细信息我想创建一个新的类对象,并调用 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()

最佳答案

您可以为此使用 input:

student4 = Student(input("Name:"), int(input("Age:")), input("Subject:"), input("ID:"))
student4.print_details()

输出:

>>> Name:Bob

>>> Age:16

>>> Subject:Maths

>>> ID:1234123

Name: Bob
Age: 16
Course: Maths
Student ID: 1234123

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

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

输出:

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

关于python - 使用用户输入启动类的新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59137302/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com