Python 音乐播放器类:面向对象设计与实现
class MusicPlayer: def init(self, name, song_list=[]): self.name = name self.song_list = song_list self.current_song = None
def play(self):
if self.current_song is None:
print("No song is selected.")
else:
print("Playing:", self.current_song)
def pause(self):
if self.current_song is None:
print("No song is selected.")
else:
print("Pausing:", self.current_song)
def next_song(self):
if self.song_list:
if self.current_song is None:
self.current_song = self.song_list[0]
else:
current_index = self.song_list.index(self.current_song)
if current_index == len(self.song_list) - 1:
self.current_song = self.song_list[0]
else:
self.current_song = self.song_list[current_index + 1]
print("Switched to:", self.current_song)
else:
print("No song is available.")
music_player = MusicPlayer("My Music Player", ["Song 1", "Song 2", "Song 3"]) music_player.play() music_player.pause() music_player.next_song() music_player.next_song() music_player.play()
原文地址: https://www.cveoy.top/t/topic/pNQr 著作权归作者所有。请勿转载和采集!