在 Python 中的 class 中将列表从一个函数传递到另一个函数

Pass a list from one function to another in a class in Python

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

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

还有一个功能是根据歌曲编号播放歌曲。如何将 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'

请注意此代码不完整。

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

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 方法的显示和读取文件名部分拆分为单独的方法。
  • 强制歌曲在播放前加载。