Python Practice › Iterator & Generator Programs › Program 8
Iterable class with a generator method
Write a class whose objects can be looped over many times.
Output
['Song A', 'Song B'] ['Song A', 'Song B']
Approach
- Make
__iter__a generator; every loop gets a fresh one.
Solution
class Playlist: def __init__(self, *songs): self.songs = songs def __iter__(self): for song in self.songs: yield song p = Playlist("Song A", "Song B")print(list(p), list(p))Output
['Song A', 'Song B'] ['Song A', 'Song B']
Learn the concept
New to this topic? Read the lesson, then come back.