處理 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隨機播放歌曲(shuffle)。 - 在
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!")
____