【问题标题】:object has no attribute python, spotify api对象没有属性python,spotify api
【发布时间】:2021-01-20 21:55:35
【问题描述】:

我正在尝试编写一个小程序,它将随机添加一首歌曲到我的 Spotify 队列中

这是我的代码;

import json
import requests
from datetime import date
from refresh import Refresh
import random
import requests
import string
import urllib


class AddSongs(object):
    def __init__(self):
        self.spotify_token = ""
        self.uri = ""

    def get_random_tracks(self):
        wildcard = f'%{random.choice(string.ascii_lowercase)}%'
        query = urllib.parse.quote(wildcard)
        offset = random.randint(0, 2000)
        url = f"https://api.spotify.com/v1/search?q={query}&offset={offset}&type=track&limit=1"
        response = requests.get(
            url,
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {self.spotify_token}"
            }
        )
        response_json = response.json()
        print(response)

        tracks = [
            track for track in response_json['tracks']['items']
        ]
        self.uri = response_json["tracks"]["items"][0]["uri"]
        


        
        print(f'Found {len(tracks)} tracks to add to your queue')

        
        
        return tracks
        return self.uri

        def add_tracks_to_queue(self,):

            print('adding to queue...')
            url =f"https://api.spotify.com/v1/me/player/queue?uri={self.uri}"
        response = requests.post(
            url,
            
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {self.api_token}"
            }
        )
        

        print(f"Added {track['name']} to your queue")

        def callrefresh(self):

            print("Refreshing token")

        refreshCaller = Refresh()

        self.spotify_token = refreshCaller.refresh()

        self.get_random_tracks()

        return response.ok 
a = AddSongs()
a. callrefresh()

这段代码给了我以下回溯。

Traceback (most recent call last):
  File "/Users/shakabediako/Documents/free_streams/main.py", line 74, in <module>
    a. callrefresh()
AttributeError: 'AddSongs' object has no attribute 'callrefresh'
>>> 

我一直在尝试解决这个问题,但没有成功。我对 python 类和类属性知之甚少,因此非常感谢您的帮助

提前感谢:)

【问题讨论】:

    标签: python api spotify


    【解决方案1】:

    这是一个缩进问题。

    您希望在类的范围内定义函数 callrefresh 和 add_tracks_to_queue,但相反,您是在 get_random_tracks 函数的范围内定义它们。

    Python 使用缩进来定义对象范围,所以因为上面的函数在 get_random_tracks 中是缩进的,所以它们在该函数的上下文中被解释,所以它们没有被添加到类方法中,因此不能被调用.

    取消缩进 callrefresh 和 add_tracks_to_queue 一级应该可以解决问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2010-10-05
      • 2014-05-14
      • 1970-01-01
      • 2012-10-04
      相关资源
      最近更新 更多