Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions Лабораторная работа 3/task_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
class Book:
""" Базовый класс книги. """

def __init__(self, name: str, author: str):
self._name = name
self._author = author

@property
def name(self) -> str:
return self._name

@property
def author(self) -> str:
return self._author

def __str__(self):
return f"Книга {self.name}. Автор {self.author}"

def __repr__(self):
return f"{self.__class__.__name__}(name={self.name!r}, author={self.author!r})"


class PaperBook(Book):
def __init__(self, name: str, author: str, pages: int):
super().__init__(name, author)
self.pages = pages

@property
def pages(self) -> int:
return self._pages

@pages.setter
def pages(self, pages: int):
if not isinstance(pages, int):
raise TypeError("Количество страниц должно быть типа int")
if pages < 1:
raise ValueError("Количество страниц должно быть положительным числом")
self._pages = pages

def __str__(self):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь, точна та же информация что и в родительском классе Book Книга и автор. Не нужно перегружать этот метод

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь, точна та же информация что и в родительском классе Book Книга и автор. Не нужно перегружать этот метод

Не совсем понял.
В методе помимо информации о книге и авторе из родительского класса Book выводится также информация о количестве страниц из самого класса PapperBook. Т.е. получается при перегрузке метода добавляет новая информация о количестве страниц в книге.
Аналогично и в AudioBook только там вместо количества страниц выводится продолжительность аудиокниги.

В любом случае я поправил код убрав перегрузку метода str из классов PapperBook и AudioBook

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Количество страниц или продолжительность книги характеризуют уже более конкретный объект - бумажную либо аудио-книгу. Эту информацию мы предоставляем именно в repr когда отображаем текстовое представление объекта, более общую суть единую для всех, а именно автора и название несёт в себе str

return f"{super().__str__()}. Страниц {self.pages}"

def __repr__(self):
return f"{super().__repr__()[:-1]}, pages={self.pages!r})"


class AudioBook(Book):
def __init__(self, name: str, author: str, duration: float):
super().__init__(name, author)
self.duration = duration

@property
def duration(self) -> float:
return self._duration

@duration.setter
def duration(self, duration: float):
if not isinstance(duration, float):
raise TypeError("Продолжительность аудиокниги должна быть типа float")
if duration <= 0:
raise ValueError("Продолжительность аудиокниги должна быть положительным числом")
self._duration = duration

def __str__(self):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Аналогично PaperBook

return f"{super().__str__()}. Продолжительность {self.duration}"

def __repr__(self):
return f"{super().__repr__()[:-1]}, duration={self.duration!r})"