Форум сайта python.su
всем добрый день. нужно модифицировать код с помощью OOП. второй день ломаю голову вот что получилось у меня(точнее не получилось)))) ниже исходный код и схема по которой нужно сделать.помогите кто может)
movies = [] class Rating(): def __init__(self,ratings): self.ratings = ratings def get_avg_rating(self,average): self.average = get_avg_rating_as_float() if self.average > 0: return str(self.average) return 'Без рейтинга' class Movie(): def __init__(self,ratings,rating): self.rating = rating self.ratings = [] def get_avg_rating_as_float(self): if len(item.rating) > 0: self.average = sum(item.rating.values()) / len(item.rating) return average return 0 # def rate(self): class MovieList(): def __init__(self): self.movies = [] def list(self): self.movies.sort(key=lambda movie: movie.name) for item in self.movies: self.average = get_avg_rating() print(f"{item.name:<25} {average:>14}") def list_average(self): self.movies = sorted(self.movies, key=self.get_avg_rating_as_float, reverse=True) for item in self.movies: average = get_avg_rating(item) print(f"{item.name:<25} {average:>14}") def find(self, name=None): name = input("Введите название фильма:\n> ") for item in self.movies: if item == name: return item return None def show(self): movie = self.find() if movie: print(f"{movie.name:^35}") for key, value in movie.items(): print(f"{key:<20} {value:>14.1f}") average = get_avg_rating(movie) print(f"{'Средний рейтинг':<20} {average:>14}") else: print("Фильм не найден") def add(self): name = input("Введите название фильма:\n> ") movie = name if movie == name: new_movie = MovieList() self.movies.append(new_movie) print("Фильм добавлен!") else: print("Такой фильм уже есть.") def rate(self): movie = self.find() if movie in self.movies: name = input("Введите ваше имя:\n> ") rating = float(input("Введите рейтинг:\n> ")) if rating == 0: if movie.ratings.get(name): movie.ratings.pop(name) elif rating < 1 or rating > 10: print("Рейтинг должен быть от 1 до 10!") else: movie[name] = rating def delete(self): movie = self.find() if movie: self.movies.remove(movie) print("Фильм удалён") else: print('Фильм не найден') # def save(movies): # with open('movies.txt', 'w') as m: # for movie in movies: # ratings = [] # for name in movie['ratings']: # ratings_str = f"{name},{movie['ratings'][name]}" # ratings.append(ratings_str) # all_ratings_str = ';'.join(ratings) # movie_str = f'{movie["name"]}|{all_ratings_str}\n' # m.write(movie_str) # def load(movies): # with open('movies.txt', 'r') as m: # for line in m: # name, all_ratings_str = line.strip().split('|') # print(name, all_ratings_str) # if all_ratings_str != '': # ratings_strings = all_ratings_str.split(';') # ratings = {} # for key in ratings_strings: # user_name, mark = key.split(',') # rating = { # user_name: float(mark) # } # ratings.update(rating) # films = { # 'name': name, # 'ratings': ratings # } # movies.append(films) @staticmethod def show_menu(): print(""" Введите команду * list - показать список фильмов * average - показать список фильмов с сортировкой по оценке * find - найти фильм * add - добавить новый фильм * rate - добавить рейтикн к фильму * delete - удалить фильм * exit - to exit""") class App(): def __init__(self): self.movie_list = MovieList() def commands(self,command): if command == 'list': self.movie_list.list() if command == 'average': self.movie_list.list_average() elif command == 'find': self.movie_list.show() elif command == 'add': self.movie_list.add() # save(movies) elif command == 'rate': self.movie_list.rate() # save(movies) elif command == 'del': self.movie_list.delete() # save(movies) def run(self): print("Добро пожаловать в телефонную книгу") MovieList.show_menu() while True: command = input("\nВведите команду: ") if command == 'exit': print("Выход") break else: self.commands(command) app = App() app.run()
movies = [] def save(movies): with open('movies.txt', 'w') as m: for movie in movies: ratings = [] for name in movie['ratings']: ratings_str = f"{name},{movie['ratings'][name]}" ratings.append(ratings_str) all_ratings_str = ';'.join(ratings) movie_str = f'{movie["name"]}|{all_ratings_str}\n' m.write(movie_str) def load(movies): with open('movies.txt', 'r') as m: for line in m: name, all_ratings_str = line.strip().split('|') print(name, all_ratings_str) if all_ratings_str != '': ratings_strings = all_ratings_str.split(';') ratings = {} for key in ratings_strings: user_name, mark = key.split(',') rating = { user_name: float(mark) } ratings.update(rating) films = { 'name': name, 'ratings': ratings } movies.append(films) def get_avg_rating(item): average = get_avg_rating_as_float(item) if average > 0: return str(average) return 'Без рейтинга' def get_avg_rating_as_float(item): if len(item['ratings']) > 0: average = sum(item['ratings'].values()) / len(item['ratings']) return average return 0 def list(movies): movies.sort(key=lambda movie: movie['name']) for item in movies: average = get_avg_rating(item) print(f"{item['name']:<25} {average:>14}") def list_average(movies): movies = sorted(movies, key=get_avg_rating_as_float, reverse=True) for item in movies: average = get_avg_rating(item) print(f"{item['name']:<25} {average:>14}") def find(movies, name=None): if not name: name = input("Введите название фильма:\n> ") for item in movies: if item['name'] == name: return item return None def show(movies): movie = find(movies) if movie: print(f"{movie['name']:^35}") for key, value in movie['ratings'].items(): print(f"{key:<20} {value:>14.1f}") average = get_avg_rating(movie) print(f"{'Средний рейтинг':<20} {average:>14}") else: print("Фильм не найден") def add(movies): name = input("Введите название фильма:\n> ") movie = find(movies, name) if not movie: new_movie = {'name': name, 'ratings': {}} movies.append(new_movie) print("Фильм добавлен!") else: print("Такой фильм уже есть.") def rate(movies): movie = find(movies) if movie is not None: name = input("Введите ваше имя:\n> ") rating = float(input("Введите рейтинг:\n> ")) if rating == 0: if movie['ratings'].get(name): movie['ratings'].pop(name) elif rating < 1 or rating > 10: print("Рейтинг должен быть от 1 до 10!") else: movie['ratings'][name] = rating def delete(movies): movie = find(movies) if movie: movies.remove(movie) print("Фильм удалён") else: print('Фильм не найден') def help(): print(""" Введите команду * list - показать список фильмов * average - показать список фильмов с сортировкой по оценке * find - найти фильм * add - добавить новый фильм * rate - добавить рейтикн к фильму * delete - удалить фильм * exit - to exit""") def menu(): help() while True: print("\nInput command: ") command = input('> ') if command == 'list': list(movies) if command == 'average': list_average(movies) elif command == 'find': show(movies) elif command == 'add': add(movies) save(movies) elif command == 'rate': rate(movies) save(movies) elif command == 'delete': delete(movies) save(movies) elif command == 'exit': break else: print("Неизвестная команда") menu()
Офлайн