我需要一些家庭作业方面的帮助:
我有一门课程,有课程名称和等级,有学生姓名和年龄的班级,学生班级中也应该有所有课程及其等级的列表
我只想使用列表。我可以用dict来做,但是可以用列表来做吗?每门课程都包含课程名称和成绩
我尝试的代码没有任何作用:
class Course:
def __init__(self,coursename,grade):
self.coursename=coursename
self.grade=int(grade)
self.newList=[]
def __str__(self):
return self.coursename+":"+ str(self.grade)
class Student:
def __init__(self,name,age):
self.name=name
self.age=int(age)
self.listCoursenamesAndGrades=[]
#super().__init__(self,coursename,grade)
def addCourse(self,c):
self.listCoursenamesAndGrades.append(c)
def __iter__(self):
self._current = 0
return self
def __next__(self):
try:
while True:
c=self.listCoursenamesAndGrades[self.current]
if (self.current <len(self.listCoursenamesAndGrades)):
self.current+=1
if c.grade > 59:
return c
except IndexError:
raise StopIteration
输出:
s1=Student("Sam",24)
C1=Course("js",80)
s1.addCourse(Course("Math",85))
s1.addCourse(Course("Math",70))
for c in s1:
print(c)
输出将是:
Js:80
Math:85
Math:70
谢谢你的帮助
问题是
__next__
应该返回一个单个项;它不应该在列表上迭代。对于您想要的内容,将迭代逻辑放在__iter__
中开始会更简单:由于
__iter__
本身不返回self
,因此可以有多个独立的迭代器(只是同时不要修改课程列表)作为使
Student
成为一个迭代器的一个例子,使用它自己的独立__next__
方法,您需要将迭代的当前状态存储在Student
本身上。例如:相关问题 更多 >
编程相关推荐