使用类和迭代的代码不能使用列表

2024-10-02 00:23:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些家庭作业方面的帮助:

我有一门课程,有课程名称和等级,有学生姓名和年龄的班级,学生班级中也应该有所有课程及其等级的列表

我只想使用列表。我可以用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

谢谢你的帮助


Tags: nameself列表agereturninitdefmath
1条回答
网友
1楼 · 发布于 2024-10-02 00:23:55

问题是__next__应该返回一个单个项;它不应该在列表上迭代。对于您想要的内容,将迭代逻辑放在__iter__中开始会更简单:

def __iter__(self):
    for c in self.listCoursenamesAndGrades:
        if c.grade > 59:
            yield c

由于__iter__本身不返回self,因此可以有多个独立的迭代器(只是同时不要修改课程列表)

作为使Student成为一个迭代器的一个例子,使用它自己的独立__next__方法,您需要将迭代的当前状态存储在Student本身上。例如:

# Since _current is an attribute of the Student instance itself,
# you can't have multiple independent iterators. Something like
#
#  i1 = iter(Student)
#  print(next(i1))
#  i2 = iter(Student)
#  print(next(i1)
#
# will print the same course twice; calling `iter(Student)` resets
# the object's iteration state.
def __iter__(self):
    self._current = 0
    return self

def __next__(self):
    try:
        while True:
            c = self.listCoursenamesAndGrades[self._current]
            self._current += 1
            if c.grade > 59:
                return c
    except IndexError:
        raise StopIteration

相关问题 更多 >

    热门问题