首页 > 解决方案 > 在 Python 的类中将列表从一个函数传递到另一个函数

问题描述

这是我在 python 中编写一个简单的 Mp3 播放器的代码。

创建了一个函数来显示文件夹中的歌曲并将它们添加到列表中:songs_list

还有另一个根据歌曲编号播放歌曲的功能。如何将歌曲列表发送到此功能?

这是我的代码:

    import os
    import sys
    import random
    from playsound import playsound
    
    
    class Mp3Player:
        def __init__(self, path):
            self.path = path
    
        def display_songs(self):
            songs_list = []
    
            for dirpath, dirname, filename in os.walk(path):
                for file in filename:
                    if file.endswith(".mp3"):
                        songs_list.append(file)
            j = 1
            for i in songs_list:
                index_of_mp3 = i.index(".mp3")
                song_list = str(j) + ". " + i[:index_of_mp3]
                j += 1
                print(song_list)
            print(" ")
    
        def play_songby_number(self, songs_list):
            song_choice = int(input("Enter song number: "))
            playsound(songs_list[song_choice - 1])
    
    
    
        def suffle_play(self):
            pass
    
    
    path = input("Enter path: ")
    my_mp3_player = Mp3Player(path)
    my_mp3_player.display_songs()
    choice_play = int(input("Please enter a choice: \n1. Play a song by it's number \n2. Shuffle play songs \nYour choice: "))
    if choice_play == 1:
        my_mp3_player.play_songby_number()
    elif choice_play == 2:
        my_mp3_player.suffle_play()
    else:
        print("Please enter a valid number")

这是我得到的错误:

Traceback (most recent call last):
  File "D:/Python Projects/MP3-Player-Python/mp3_player_v1.0.py", line 41, in <module>
    my_mp3_player.play_songby_number()
TypeError: play_songby_number() missing 1 required positional argument: 'songs_list'

请注意,此代码不完整。

标签: pythonclassaudiomp3

解决方案


您可以尝试将类中的歌曲列表保存为实例属性并使用它。

import os
import sys
import random
from playsound import playsound


class Mp3Player:
    def __init__(self, path):
        self.path = path
        self.song_list = None

    def display_songs(self):
        songs_list = []

        for dirpath, dirname, filename in os.walk(path):
            for file in filename:
                if file.endswith(".mp3"):
                    songs_list.append(file)
        j = 1
        for i in songs_list:
            index_of_mp3 = i.index(".mp3")
            song = str(j) + ". " + i[:index_of_mp3]
            j += 1
            print(song)
        # save the song_list in the instance
        self.song_list = songs_list
        print(" ")

    def play_songby_number(self):
        # use the song list from the instance
        if not self.song_list:
            raise Exception("No songs loaded yet. Try displaying songs before playing")
        song_choice = int(input("Enter song number: "))
        playsound(self.song_list[song_choice - 1])

    def suffle_play(self):
        pass


path = input("Enter path: ")
my_mp3_player = Mp3Player(path)
my_mp3_player.display_songs()
choice_play = int(
    input("Please enter a choice: \n1. Play a song by it's number \n2. Shuffle play songs \nYour choice: "))
if choice_play == 1:
    my_mp3_player.play_songby_number()
elif choice_play == 2:
    my_mp3_player.suffle_play()
else:
    print("Please enter a valid number")

一些让事情变得更清洁的建议。

  • 将方法的显示和读取文件名部分拆分display_songs为单独的方法。
  • 强制在播放歌曲之前加载歌曲。

推荐阅读