1
resposta

[Sugestão] Possível solução

Criei diversos produtos no arquivo products.py

from model import Movie, Series, Playlist

products = {
    "movie_1": Movie("Avengers", 2009, 160),
    "series_1": Series("Sopranos", 1999, 6),
    "movie_2": Movie("Sentinelle", 1992, 139),
    "movie_3": Movie("Scream", 1996, 111),
    "series_2": Series("The Wire", 2002, 5),
}

products["movie_1"].add_like(3)
products["movie_1"].name = "the AveNgers"
products["series_1"].add_like(2)
products["movie_2"].add_like(0)
products["movie_2"].name = "la sentinelLe"
products["movie_3"].add_like(9)
products["series_2"].add_like(4)

new_movies = [
    Movie("The Godfather", 1972, 175),
    Movie("The Dark Knight", 2008, 152),
    Movie("Honey, I Shrunk the Kids", 1989, 93),
]

new_movies[0].add_like(4)
new_movies[1].add_like(6)
new_movies[2].add_like(2)

items = list(products.values()) + new_movies
weekend = Playlist("Weekend", items)

Eis o modelo em model.py

class Watchable:
    _id_tracker = 0

    def __init__(self, name, year):
        self._name = name.title()
        self.year = year
        self._likes = 0
        self._id = self.new_id()

    def __str__(self):
        return f"{self.name} ({self.year}) - {self.likes} likes"

    def __repr__(self):
        return f"{self.__class__.__name__}(name={self.name}, year={self.year}, likes={self.likes}, id={self.id})"

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, new_name):
        if not new_name:
            raise ValueError("Gotta have a name!")
        self._name = new_name.title()

    @property
    def likes(self):
        return self._likes

    @likes.setter
    def likes(self, new_amount):
        if not isinstance(new_amount, int):
            raise TypeError("Amount of likes needs to be an integer.")
        if new_amount < 0:
            raise ValueError("There are no negative likes.")
        self._likes = new_amount

    @property
    def id(self):
        return self._id

    @property
    def type(self):
        return self.__class__.__name__

    @classmethod
    def new_id(cls):
        cls._id_tracker += 1
        return cls._id_tracker

    def add_like(self, occurrences):
        if occurrences < 0:
            raise ValueError("Can't decrement likes.")
        self.likes += occurrences

    def _add_trashcan_icon(self):
        return f" - \U0001F5D1" if self.likes == 0 else ""


class Movie(Watchable):

    def __init__(self, name, year, length):
        super().__init__(name, year)
        self.length = length

    def __str__(self):
        trash = self._add_trashcan_icon()
        return f"{self.name} ({self.year}) - {self.length} min - {self.likes} likes{trash}"


class Series(Watchable):

    def __init__(self, name, year, seasons):
        super().__init__(name, year)
        self.seasons = seasons

    def __str__(self):
        formatted_seasons = SmallNumberFormatter.format_small_numbers(
            self.seasons)
        trash = self._add_trashcan_icon()
        return f"{self.name} ({self.year}) - {formatted_seasons} seasons - {self.likes} likes{trash}"


class Playlist:

    def __init__(self, name, items):
        self.name = name
        self.items = items

    def __str__(self):
        formatted_size = SmallNumberFormatter.format_small_numbers(
            self.size()) if self.size() >= 10 else self.size()
        playlist_str = f"Here's your {self.name} playlist with {formatted_size} items total:\n"
        for index, item in enumerate(self.items):
            playlist_str += f"{index + 1}) {item} ({item.id})\n"
        return playlist_str

    def size(self):
        return len(self.items)

    def average_likes(self):
        return sum(
            item.likes
            for item in self.items) / self.size() if self.size() > 0 else 0

    def total_movie_runtime(self):
        return sum(item.length for item in self.items
                   if isinstance(item, Movie))


class SmallNumberFormatter:
    WORDS = {
        number: word
        for number, word in enumerate(
            'zero one two three four five six seven eight nine ten'.split(), 0)
    }

    @staticmethod
    def format_small_numbers(number):
        return SmallNumberFormatter.WORDS.get(number, str(number))

E seu uso em main.py

from products import products, new_movies, items, weekend

print(weekend)
print(f"Your collection has an average of {weekend.average_likes():.2f} likes.")
print(f"Your total movie runtime is {weekend.total_movie_runtime()} minutes.")
1 resposta

Olá Rafael, tudo bem?

Fico feliz em ver sua participação no fórum da Alura, sempre compartilhando seus aprendizados e evolução, continue contribuindo para o crescimento da comunidade do fórum Alura. Suas postagens com seus projetos serão inspiração para os estudantes que lerem suas postagens.

Abraços e bons estudos!