处理 StopIteration 错误
上一练习中的 Playlist 类已经更新,会打印当前正在播放的歌曲名称,代码如下。使用这个自定义迭代器,您将练习优雅地处理 StopIteration 异常。祝您练习愉快!
class Playlist:
def __init__(self, songs, shuffle=False):
self.songs = songs
self.index = 0
if shuffle:
random.shuffle(self.songs)
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.songs):
raise StopIteration
print(f"Playing {self.songs[self.index]}")
self.index += 1
本练习是课程的一部分
Python 面向对象编程进阶
练习说明
- 创建一个名为
classic_rock_playlist的Playlist,由songs列表中的标题构成;请确保classic_rock_playlist会打乱歌曲顺序。 - 在
while循环中使用try-except代码块,播放classic_rock_playlist的下一首歌。 - 更新
try-except逻辑来处理StopIteration错误,打印一条消息,并跳出循环。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create a classic rock playlist using the songs list
songs = ["Hooked on a Feeling", "Yesterday", "Mr. Blue Sky"]
____ = ____(____, ____=True)
while True:
____:
# Play the next song in the playlist
next(____)
# If there is a StopIteration error, print a message and
# stop the playlist
____ ____:
____("Reached end of playlist!")
____