我想编码电影分类类,它可以找到(基于一些标准),添加和打印电影。你知道吗
这是我的密码:
class Movie:
def __init__(self,name,director,year,location):
self.name = name
self.director = director
self.year = year
self.location = location
self.information = {'name':self.name,'director':self.director,'year':self.year,'location':self.location}
def get_name(self):
return self.name
def get_director(self):
return self.director
def get_year(self):
return self.year
def get_location(self):
return self.location
def get_information(self):
return self.information
def __str__(self):
return f"Name = {self.name},director = {self.director},year = {self.year},location = {self.location}"
class Classification:
def __init__(self):
self.movie_list = []
def length(self):
return len(self.movie_list)
def __getitem__(self,key):
if isinstance(self.movie_list,slice):
return self.movie_list[key]
def add_movie(self,movie):
self.movie_list.append(movie)
def print_movie(self):
for movie in self.movie_list:
print(movie)
def find_movie(self,**kwargs):
check_list = []
for movie in self.movie_list:
for name,value in kwargs.items():
if movie.get_information()[name] == value:
check_list.append(True)
else:
check_list.append(False)
if all(item == True for item in check_list):
print(movie)
check_list.clear()
这里我有一个类Movie
,Classification
;Classification
只有一个属性,这是电影列表。但我有两个问题:
a = Movie('Matrix','Dan Yefimov','1999','New York')
b = Movie('Legend','Mak Markus','2005','Kiev')
clasif = Classification()
clasif.add_movie(a)
clasif.add_movie(b)
clasif.find_movie(location = 'New York')
find_movie()
适用于列表中的第一部电影(a
)。但是对于第二个,它什么也不打印,即使我输入了正确的搜索参数。
切片不起作用。没有错误信息,只是没有打印任何内容。
你能帮我解决问题吗?你知道吗
另外,我还想听听一些关于改进我的代码的一般性建议。你知道吗
通过删除不必要的方法,我们可以大大缩短代码。我们也可以将
__getitem__
传递给列表。我还会在定义length
方法时使用__len__
。你知道吗以下是您的代码版本,代码会稍微少一点:
我在
Movie
中添加了一个名为ATTRIBUTES
的类属性;这在Movie.__str__()
和Classification.find_movies()
中都有使用。建议避免在代码中大量重复属性。你知道吗在方法
Classification.find_movies()
中,我先检查它是否是有效的属性,然后再将它与电影实例进行比较。无效参数将被忽略,但您可以更改代码,使无效参数自动导致电影无法打印(所有将被排除)。你知道吗相关问题 更多 >
编程相关推荐