简体   繁体   English

将变量传递给 function 然后传递给 class

[英]Passing a variable into a function and then to a class

I'm new to Python and had made a script which displays random songs from a JSON file.我是 Python 的新手,并且制作了一个脚本,它显示来自 JSON 文件的随机歌曲。 It was working fine, but I thought that I'd venture into the world of classes to make parts of it reusable.它工作得很好,但我认为我会冒险进入类的世界以使其部分可重用。

Now I can't get the class to present the random result.现在我无法让 class 呈现随机结果。

This is the class which I also use when I want to play a specific song:这是 class,当我想播放特定歌曲时也会使用它:

songid = int()

class songDetails():
    def __init__(self, songId, songName, artist, key, mode, tempo, proficiency, uuid) -> None:
        self.songId = songId
        self.songName = songName
        self.artist = artist
        self.key = key
        self.mode = mode
        self.tempo = tempo
        self.proficiency = proficiency
        self.uuid = uuid
        
    def songCard(self):
        # songId = random
        print(f"{self.songId}")
        print(f"{self.songName}, by {self.artist}")
        print(f"Key: {keys[self.key]}{modes[self.mode]}")
        print(f"BPM: {self.tempo}")
        print(f"{proficiencyLevel[self.proficiency]}\n")

Because I had so many JSON references throughout the script, I decided to build a function that stored each as a variable因为我在整个脚本中有很多 JSON 引用,所以我决定构建一个 function 将每个引用存储为一个变量

def readSongsJSON():
    # songId = randomSong()
    try:
        global songId
        songsJSON = pd.read_json(data)
        songItems = songsJSON['songbook']['songs']
        songAllInfo = songsJSON['songbook']['songs'][songId]
        songName = songsJSON['songbook']['songs'][songId]['song']
        songArtist = songsJSON['songbook']['songs'][songId]['artist']
        songKey = songsJSON['songbook']['songs'][songId]['key']
        songMode = songsJSON['songbook']['songs'][songId]['mode']
        songTempo = songsJSON['songbook']['songs'][songId]['tempo']
        songKeyConfidenceAvg = songsJSON['songbook']['songs'][songId]['keyConfidenceAvg']
        songProficiency = songsJSON['songbook']['songs'][songId]['proficiency']
        songUUID = songsJSON['songbook']['songs'][songId]['uuid']
        songCategory = songsJSON['songbook']['songs'][songId]['category']
        songSpotifyURI = songsJSON['songbook']['songs'][songId]['spotifyURI']
        songVideo = songsJSON['songbook']['songs'][songId]['video']
    except:
        print("Cannot access data ")

    return songItems, songAllInfo, songName, songArtist, songKey, songMode, songTempo, songKeyConfidenceAvg, songProficiency, songUUID, songCategory, songSpotifyURI, songVideo

Finally, this is the function that is triggered from a Typer command:最后,这是由 Typer 命令触发的 function:

def randomSong():
    # Open JSON file

    songItems, songAllInfo, songName, songArtist, songKey, songMode, songTempo, songKeyConfidenceAvg, songProficiency, songUUID, songCategory, songSpotifyURI, songVideo = readSongsJSON()
    randomSong = random.choice(songItems)
    randomUUID = randomSong['uuid']

    songIterator = 0
 
    for x in songItems:
        if randomUUID == songItems[songIterator]['uuid']:
            song = songDetails(
                songId,
                songName,
                songArtist,
                songKey,
                songMode,
                songTempo,
                songProficiency,
                songUUID
                )
                 # DISPLAY THE SONG CARD
                 song.songCard()
            break
        else:
            songIterator += 1
    # print(songIterator)

I guess my challenge is, how do I get the random songID to be assigned to the content in readSongsJSON and then displayed in the Class output?我想我的挑战是,如何将随机歌曲 ID 分配给songID中的内容,然后显示在readSongsJSON output 中?

I've tried a range of options, but the songId always stays as 0.我尝试了一系列选项,但songId始终保持为 0。

Your current structure is您当前的结构是

  1. A class to print the info of the random song A class 打印随机歌曲信息
  2. A function to load all songs, and get the info of a song based on songId (global variable) A function 加载所有歌曲,根据songId(全局变量)获取歌曲信息
  3. A function to get a random song from list of all songs, and use iterations to find the song information, if it matches, run class in step 0 to print the info of the song A function 从所有歌曲列表中随机获取一首歌曲,并使用迭代查找歌曲信息,如果匹配,则在步骤0中运行 class以打印歌曲信息

Seem like you are squeezing 2 functions in step 1, but the latter function (get the info of a song) should come after selecting a random songId in step 2. You can do似乎您在第 1 步中挤压了 2 个功能,但后者 function (获取歌曲信息)应该在第 2 步中选择随机 songId 之后出现。您可以

  1. A class to print the info of the random song A class 打印随机歌曲信息
  2. A function to load all songs A function 加载所有歌曲
  3. A function to get the info of a song based on songId A function 根据songId获取歌曲信息
  4. A function to get a random song from list of all songs, run function in step 2 to get the info of the song, run class in step 0 to print the info of the song A function 从所有歌曲列表中获取随机歌曲,在步骤 2 中运行 function以获取歌曲信息,在步骤 0 中运行 class以打印歌曲信息
class songDetails():
    def __init__(self, songId, songName, artist, key, mode, tempo, proficiency, uuid) -> None:
        self.songId = songId
        self.songName = songName
        self.artist = artist
        self.key = key
        self.mode = mode
        self.tempo = tempo
        self.proficiency = proficiency
        self.uuid = uuid
        
    def songCard(self):
        # songId = random
        print(f"{self.songId}")
        print(f"{self.songName}, by {self.artist}")
        print(f"Key: {keys[self.key]}{modes[self.mode]}")
        print(f"BPM: {self.tempo}")
        print(f"{proficiencyLevel[self.proficiency]}\n")
def readSongsJSON():
    try:
        songsJSON = pd.read_json(data)
        songItems = songsJSON['songbook']['songs']
    except:
        print("Cannot access data ")
    return songItems

def readSongInfo(songId, songItems):
    songAllInfo = songItems[songId]
    songName = songAllInfo['song']
    songArtist = songAllInfo['artist']
    songKey = songAllInfo['key']
    songMode = songAllInfo['mode']
    songTempo = songAllInfo['tempo']
    songKeyConfidenceAvg = songAllInfo['keyConfidenceAvg']
    songProficiency = songAllInfo['proficiency']
    songUUID = songAllInfo['uuid']
    songCategory = songAllInfo['category']
    songSpotifyURI = songAllInfo['spotifyURI']
    songVideo = songAllInfo['video']
    return songAllInfo, songName, songArtist, songKey, songMode, songTempo, songKeyConfidenceAvg, songProficiency, songUUID, songCategory, songSpotifyURI, songVideo
def randomSong():
    # Open JSON file
    songItems = readSongsJSON()

    # randomly select a songId
    songId = random.choice(range(len(songItems)))
    
    # get the info of the song
    songAllInfo, songName, songArtist, songKey, songMode, songTempo, songKeyConfidenceAvg, songProficiency, songUUID, songCategory, songSpotifyURI, songVideo = readSongInfo(songId, songItems)

    song = songDetails(
        songId,
        songName,
        songArtist,
        songKey,
        songMode,
        songTempo,
        songProficiency,
        songUUID
        )
    # DISPLAY THE SONG CARD
    song.songCard()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM