我的问题是我创建了一个带有姓名和编号的学生列表。现在的任务是按学生的编号删除学生。我的问题是我的代码不起作用。
另一个问题是它总是显示内存地址而不是对象的值。
提前致谢
班级学生:
def __init__(self, name, number):
self.name = name
self.number = number
from .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))
from .course import 课程类部:
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))
from python import * 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()
self.students
是一个Student
实例列表,因此如果__str__
未实现该方法,它将打印实例的内存地址(例如参见此处)。您应该尝试像student.name
或student.number
显式地打印每个属性。
无论如何,您正在尝试student_number
在列表中查找,Student
因此它当然永远不会运行删除行。而是使用if student_number in [student.number for student in self.students]
which 正在查找学生的编号列表,而不是学生列表本身。但是在这种情况下,您还想删除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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句