【发布时间】:2022-01-14 14:18:27
【问题描述】:
我有一个具有空字典属性的类:
class Library:
def __init__(self,library):
self.library={}
def addSong(self,title,artist,genre,playCount):
for i in self.library.keys():
if i == title:
x=self.library.get(title)
x[2]= x[2]+1
else:
self.library[title]=[artist,genre,playCount]
def song2String(self,title):
x=self.library.get(title)
return f"{x[0]} {title} ({x[1]}), {x[2]}"
现在当我这样做时:
m1= Library({})
m1.addSong("Saturday Night's Alright for Fighting","Elton John","Rock",22)
代码运行正常,项目被添加到m1 字典中。
但是当我输入这个时:
print(m1.song2String("Saturday Night's Alright for Fighting"))
我收到此错误消息:
return f"str{x[0]} str{title} (str{x[1]}), str{x[2]}"
TypeError: 'NoneType' object is not subscriptable
我的语法错误是什么?
【问题讨论】:
-
self.library.get(title)正在返回None,这表明title不是self.library中的键,或者self.library[title]处的值是None。 -
确定要加+1而不是+playcount?,比如用22调用两次,应该是23还是44?
-
"代码运行正常,项目被添加到 m1 字典中。" 你确定?你怎么知道的?
标签: python class dictionary syntax