/
nk1383
/
oop
Обзор
Документация
Войти
/
nk1383
/
oop
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
third.py
60 строк
2 KB
Анастасия Ковалевич
upload files
24 окт 2025, 17:31
24 окт 2025, 17:31
681107c
Код
Авторство
О чём код?
from datetime import datetime class Book: def __init__(self, title: str, author: str, year: int) -> None: self.title = title self.author = author self.year = year def info(self) -> str: return f"Title: {self.title}, author: {self.author}, year: {self.year}" def __str__(self) -> str: return f'"{self.title}" by {self.author} ({self.year})' def __eq__(self, other: object) -> bool: if not isinstance(other, Book): return False return ( self.title == other.title and self.author == other.author and self.year == other.year ) @property def age(self) -> int: current_year = datetime.now().year return current_year - self.year @classmethod def from_string(cls, book_str: str) -> "Book": try: title, author, year_str = book_str.split(",") title = title.strip() author = author.strip() year = int(year_str.strip()) return cls(title, author, year) except (ValueError, IndexError) as e: raise ValueError(f"Неверный формат строки для книги: {book_str}") from e class Ebook(Book): def __init__(self, title: str, author: str, year: int, format_: str) -> None: super().__init__(title, author, year) self.format = format_ def info(self) -> str: return super().info() + f", format: {self.format}" if __name__ == "__main__": book = Book("Гарри Поттер", "Дж. Роулинг", 1997) book2 = Book.from_string("Властелин колец, Дж. Р. Р. Толкин, 1954") book3 = Book("Гарри Поттер", "Дж. Роулинг", 1997) print(book == book3) print(book2) print(f"Возраст: {book2.age} лет") print(book.info()) print(book3.age)