Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 基于输入,如何将列表中的元素分类为类的对象?_Python 3.x_List_Class - Fatal编程技术网

Python 3.x 基于输入,如何将列表中的元素分类为类的对象?

Python 3.x 基于输入,如何将列表中的元素分类为类的对象?,python-3.x,list,class,Python 3.x,List,Class,我有密码: class tune: def __init__(self, title, artist, duration): self.title = title self.artist = artist self.duration = duration class play: def __init__(self): self.tracks = [] def add(self, song): se

我有密码:

class tune:
    def __init__(self, title, artist, duration):
        self.title = title
        self.artist = artist
        self.duration = duration
class play:

    def __init__(self):
        self.tracks = []

    def add(self, song):
    self.tracks.append[song]
    
    def look(self,song):
    print (self.artist,"-",self.title)

n=input() #number of input
song=play()
for i in range(n):
    x = input().split(',')
    song.title=x[1]
    song.artist=x[0]
    song.duration=x[2]
song.look()
对于每个输入,我必须使其成为与其类相关的对象,并将其添加到列表中。调用song.look时,应该打印列表中的标题和艺术家。例如,如果输入为:

2
Artic Monkeys,R U Mine?,324
Artic Monkeys,Do I wanna know?,253
执行程序时,应输出:

Artic Monkeys - R U Mine?
Artic Monkeys - Do I wanna know?

我不知道我是否将输入分别附加到了它的对象,我是否做错了什么?

您没有提供太多关于问题所在的上下文,但从您的代码来看,这有点明显。尝试使用以下方法:

类调谐:
定义初始(自我、头衔、艺术家、持续时间):
self.title=标题
self.artist=艺术家
self.duration=持续时间
班级游戏:
定义初始化(自):
self.tracks=[]
def添加(自我、歌曲):
self.tracks.append(歌曲)
def外观(自我、歌曲):
对于self.tracks中的歌曲:
印刷品(f“{song.artist}-{song.title}”)
n=int(输入(“输入要添加的曲目数”))
playlist=Play()
对于范围(n)中的i:
标题、艺术家、持续时间=输入(“输入曲目的标题、艺术家和持续时间”)。拆分(“,”)
歌曲=曲调(标题、艺术家、持续时间)
播放列表。添加(歌曲)
playlist.look()