我有一个类,它有一个空的字典属性:
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我的语法错误是什么?
发布于 2021-12-09 18:54:44
您在library键上迭代:for i in self.library.keys(),但是由于没有,什么也不做,使其工作的最小更改是
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
break
else:
self.library[title] = [artist, genre, playCount]但是最好的方法就是测试标题是否存在,然后做正确的事情。
def addSong(self, title, artist, genre, playCount):
if title in self.library:
self.library[title][2] += playCount
else:
self.library[title] = [artist, genre, playCount]发布于 2021-12-09 18:55:48
当前代码不返回任何内容,这是导致错误的原因。我不知道你为什么要用钥匙插入你的歌,直接用字典就行了:
class Library:
def __init__(self,library):
self.library={}
def addSong(self,title,artist,genre,playCount):
if title in self.library: ## changed code here and below
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)
print(m1.library)
# {"Saturday Night's Alright for Fighting": ['Elton John', 'Rock', 22]}
print(m1.song2String("Saturday Night's Alright for Fighting"))
# Elton John Saturday Night's Alright for Fighting (Rock), 22发布于 2021-12-09 19:28:27
,我想这是你所期望的。在这里的加载项函数中,我首先检查的是字典中可用的任何键。如果是真的,那就迭代,做你想做的事。否则,将第一个字典项添加到字典中。在songs2string方法中,首先要识别字典是如何工作的。在这种情况下,键是字符串,值是字典中的列表。所以你可以用字典返回你想要的东西。
class Library:
def __init__(self,library=dict()):
self.library=library
def addSong(self,title,artist,genre,playCount):
if len(self.library.keys())>0:
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]
# print(self.library)
def song2String(self,title):
x=self.library
print(x)
return x[title][0], x[title][1], x[title][2]
m1= Library()
m1.addSong("Saturday Night's Alright for Fighting","Elton John","Rock",22)
print(m1.song2String("Saturday Night's Alright for Fighting"))https://stackoverflow.com/questions/70295196
复制相似问题