【发布时间】:2021-04-26 02:30:27
【问题描述】:
我在尝试运行的一个小 spotify-api 程序中有一个属性错误
我的运行文件包含以下内容
import os
from spotify_client import AddSongs
def run():
spotify_client = AddSongs('spotify_token')
random_tracks = spotify_client.get_random_tracks()
track_ids = [track['id'] for track in random_tracks]
was_added_to_queue = spotify_client.add_tracks_to_queue()
if was_added_to_queue:
for track in random_tracks:
print(f"Added {track['name']} to your library")
if __name__ == '__main__':
run()
那么在 spotify_client 中是下面的类
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.spotify_token}"
}
)
print(f"Added {track['name']} to your queue")
return response.ok
def callrefresh(self):
print("Refreshing token")
refreshCaller = Refresh()
self.spotify_token = refreshCaller.refresh()
self.get_random_tracks()
a = AddSongs()
a. callrefresh()
如您所见,它可以正常运行代码,直到 add_tracks_to_queue 这给了我以下回溯
Refreshing token
<Response [200]>
Found 1 tracks to add to your queue
Traceback (most recent call last):
File "/Users/shakabediako/Documents/free_streams/run.py", line 18, in <module>
run()
File "/Users/shakabediako/Documents/free_streams/run.py", line 7, in run
spotify_client = AddSongs('spotify_token')
TypeError: __init__() takes 1 positional argument but 2 were given
>>>
我知道关于这个错误有多个线程,但在阅读了其中大部分之后,我无法理解这个概念或找到答案。 我认为这与我从另一个文件调用函数有关,但我不明白为什么这会创建另一个“位置参数” 我知道这一点,因为如果我只运行 spotify_client 文件,我会得到以下响应
Refreshing token
<Response [200]>
Found 1 tracks to add to your queue
>>>
这只是我在 def add_tracks_to_queue 之前的打印值(我也不明白为什么它没有运行)
我真的希望有人可以帮助我 提前致谢
【问题讨论】:
-
AddSongs('spotify_token')和AddSongs.__init__(self,):你看到问题了吗? -
按照惯例,类名通常是名词,方法名是动词。你的
AddSongs类看起来代表一个 Spotify 帐户;添加歌曲是您可以在与帐户关联的播放列表上执行的操作。