python - 简单电影数据库错误,python 类型可统一

我正在尝试设计一些接受电影标题和持续时间输入的代码,将它们添加到一个对象中,然后对其进行排序并打印三个最长的电影,它运行到最后一行然后失败,我应该如何以不同的方式做呢?

class Movie:
    def __init__(self, title, duration):
        self.title = title
        self.duration = duration


def get_movie_duration(movie):
    return movie.duration


class MovieCollection:
    def __init__(self):
        self.movies = []

    def add_movie(self, movie):
        self.movies.append(movie)
    
    def print_longest_movies(self):
        sorted(Movie, key=get_movie_duration, reverse = True)
        print('1. '+ str(Movie.title[0]) + str(Movie.duration[0]))
        print('2. '+ str(Movie.title[1]) + str(Movie.duration[1]))
        print('3. '+ str(Movie.title[2]) + str(Movie.duration[2]))

collection = MovieCollection()
while True:
    title = input('Movie title (or blank to finish): ')
    if title == '':
        break
    duration = int(input('Movie duration (minutes): '))
    Movie.title = title
    Movie.duration = duration
    collection.add_movie(Movie)


print('\n= Longest movies in the collection =')
collection.print_longest_movies()

回答1

您的 print_longest_movies 函数混淆了对象列表及其类型之间的区别。 Movie 不是事物的列表。这只是类的名称。另外, sorted 返回排序后的数组。它不会改变数组。你要:

def print_longest_movies(self):
        self.movies.sort(key=get_movie_duration, reverse = True)
        print('1.', self.movies[0].title, self.movies[0].duration)
        print('2.', self.movies[1].title, self.movies[1].duration)
        print('3.', self.movies[2].title, self.movies[2].duration)

创建列表时,您也有同样的困惑。您要创建类的实例,而不是使用类名:

while True:
    title = input('Movie title (or blank to finish): ')
    if title == '':
        break
    duration = int(input('Movie duration (minutes): '))
    collection.add_movie(Movie(title, duration))

相似文章

最新文章