[英]Python, new unique object for each user input
初级程序员在这里。 我创建了一个 class 使学生成为 object,我需要一种方法来为用户创建的每个 object 不覆盖以前的对象并使它们完全相同。 这可能是一个糟糕的解释,所以我将只发布代码和 output。
class Student:
"""This class holds student records """
student_id = 000
def __init__(self,firstname='blank',lastname='blank',age=0,sex='NA',major='undeclared',graduation=0):
self.firstname = firstname
self.lastname = lastname
self.age = age
self.sex = sex
self.major = major
self.graduation= graduation
Student.student_id +=1
self.student_id = Student.student_id
students=[]
while True:
new_student=Student(input('Enter student first name: '),input('Enter student last name: '),input('Enter student age: '),input("Enter student sex: "),input("Enter student's major: "),input("Enter student's expected graduation date: "))
students.append(new_student)
add_another=input("Would you like to add another student? Enter 'Y' for yes or any other key to quit and print your entries: ")
if add_another == 'Y':
continue
else:
for i in students:
print(new_student.firstname)
print(new_student.student_id)
break
我的 output 目前看起来像这样:
Enter student first name: Thomas
Enter student last name: Hutton
Enter student age: poop
Enter student sex: p
Enter student's major: p
Enter student's expected graduation date: p
Would you like to add another student? Enter 'Y' for yes or any other key to quit and print your entries: Y
Enter student first name: Timmy
Enter student last name: p
Enter student age: p
Enter student sex: p
Enter student's major: p
Enter student's expected graduation date: p
Would you like to add another student? Enter 'Y' for yes or any other key to quit and print your entries: n
Timmy
2
Timmy
2
如您所见,现在填充学生列表的唯一 object 现在对于两个条目都是相同的 object,我需要它们是用户提供的条目。 谢谢你的帮助。
您正在创建的 object 并没有覆盖之前的,问题出在您的打印循环上:
for i in students:
print(new_student.firstname)
print(new_student.student_id)
break
它不会打印列表中的所有学生,它总是打印最后添加的学生(这是new_student
变量)。 要解决这个问题,你可以这样做:
for student in students:
print(student.firstname)
print(student.student_id)
break
当您遍历学生时,您没有引用正确的变量。 new_student
应该是i
for i in students:
print(i.student_id)
print(i.firstname)
但我建议将 i 变量更改为学生,所以它看起来像
for student in students:
print(student.firstname)
i
通常用于表示列表中的 integer 索引。
您不需要临时的new_student
。
只需将 append 直接添加到学生列表中,而不使用(不是这样)临时变量。 与提示另一个相同。
class Spam:
"""Spiced meat"""
def __init__(self, firstname=''):
self.firstname = firstname
def __repr__(self):
return self.firstname
lunch = []
while True:
lunch.append(Spam(input('Enter name: ')))
if input('Another one? ') in ('y', 'Y'):
continue
else:
break
for meat in lunch:
print(meat)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.