Unable to run a simple python program
我开始学Python。下面是一个简单的程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | class StudentRepo: def __init__(self): self.student_list = [] def add(self, student): self.student_list.append(student) def get_list(self): self.student_list class Student: def __init__(self, name, age): self.age = age self.name = name from models.student.Student import Student from services.student.StudentRepo import StudentRepo s1 = Student("A", 10) s2 = Student("B", 11) # What is the issue here ? StudentRepo.add(s1) StudentRepo.add(s2) studentList = StudentRepo.get_list() for student in studentList: print(student.name) |
您的代码中有两个错误。首先,这是:
1 2 | def get_list(self): self.student_list |
应该是:
1 2 | def get_list(self): return self.student_list |
其次,您使用的是类
1 2 3 4 5 6 7 8 9 10 11 | s1 = Student("A", 10) s2 = Student("B", 11) my_roster = StudentRepo() my_roster.add(s1) my_roster.add(s2) studentList = my_roster.get_list() for student in studentList: print(student.name) |