下面是一个示例代码,演示如何实现在播放列表中不移除上一首歌曲:
class Playlist:
def __init__(self):
self.songs = []
self.current_song = None
def add_song(self, song):
self.songs.append(song)
def play(self):
if self.current_song is None:
if len(self.songs) > 0:
self.current_song = self.songs[0]
print("Now playing:", self.current_song)
else:
print("No songs in the playlist.")
else:
print("Resuming playback of:", self.current_song)
def next_song(self):
if self.current_song is None:
print("No song is currently playing.")
else:
index = self.songs.index(self.current_song)
if index < len(self.songs) - 1:
self.current_song = self.songs[index + 1]
print("Playing next song:", self.current_song)
else:
print("End of playlist.")
def previous_song(self):
if self.current_song is None:
print("No song is currently playing.")
else:
index = self.songs.index(self.current_song)
if index > 0:
self.current_song = self.songs[index - 1]
print("Playing previous song:", self.current_song)
else:
print("Beginning of playlist.")
# 创建一个播放列表对象
my_playlist = Playlist()
# 添加歌曲到播放列表
my_playlist.add_song("Song 1")
my_playlist.add_song("Song 2")
my_playlist.add_song("Song 3")
# 播放歌曲
my_playlist.play()
# 播放下一首歌曲
my_playlist.next_song()
# 播放上一首歌曲
my_playlist.previous_song()
这个示例中,Playlist
类有一个 add_song
方法用于添加歌曲到播放列表,play
方法用于播放歌曲,next_song
方法用于播放下一首歌曲,previous_song
方法用于播放上一首歌曲。播放列表中的歌曲存储在一个列表中,current_song
属性保存当前正在播放的歌曲。当调用 play
方法时,如果当前没有正在播放的歌曲,会播放第一首歌曲,否则会继续播放当前的歌曲。当调用 next_song
方法时,会播放下一首歌曲,如果已经是最后一首歌曲,则会提示播放列表已经结束。当调用 previous_song
方法时,会播放上一首歌曲,如果已经是第一首歌曲,则会提示已经到达播放列表的开始。
下一篇:不要让一个方块超过第二个方块