我的问题是我创建了一个带有姓名和号码的学生列表。现在的任务是按学生的号码删除该学生。我的问题是我的代码无法正常工作。
另一个问题是它总是显示内存地址而不是对象的值。
预先感谢
班级学生:
def __init__(self, name, number):
self.name = name
self.number = number
从.student导入Student 课程:
def __init__(self, name, code, credit, student_limit):
self.name = name
self.code = code
self.credit = credit
self.student_limit = student_limit
students = []
def add_student(self, new_student):
self.student = new_student
self.students.append(new_student)
print("Student added" +str(self.students))
def remove_student_by_number(self, student_number):
self.student_number = student_number
if student_number in self.students: self.students.remove(student_number)
print("Student removed" + str(self.students))
来自.course导入课程 班系:
def __init__(self, name, code):
self.name = name
self.code = code
courses = []
def add_course(self, course):
self.course = course
self.courses.append(course)
print("Course added" +str(self.courses))
从python导入* def main():
alice = Student("Alice", 1336)
bob = Student("Bob", 1337)
math_dept = Department("Mathematics and Applied Mathematics", "MAM")
math_course = Course("Mathematics 1000", "MAM1000W", 1, 10)
math_dept.add_course(math_course)
math_course.add_student(bob)
math_course.add_student(alice)
math_course.remove_student_by_number(alice.number)
if __name__ == "__main__":
main()
答案 0 :(得分:1)
self.students
是Student
实例的列表,因此如果未实现方法__str__
(例如,请参见here),它将打印实例的内存地址。您应该尝试显式打印每个属性,例如student.name
或student.number
。
无论如何,您都试图在student_number
的列表中找到Student
,因此,它绝不会运行删除行。而是使用if student_number in [student.number for student in self.students]
来查找学生的号码列表,而不是学生列表本身。但是,在这种情况下,您还想删除以student_number
作为输入的学生,因此您可能需要使用如下循环:
def remove_student_by_number(self, student_number):
for student in self.students:
if student.number == student_number:
print("Student removed" + str(student.name))
self.students.remove(student)
break