-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
task_2_flat #4
base: main
Are you sure you want to change the base?
task_2_flat #4
Conversation
task_2_flat
Outdated
class_f = Flat('kitchen', 'bedroom', 'bathroom') | ||
class_f.print_rooms() | ||
class_f.print_flat_size(4, 5, 6) | ||
class_f.print_bathroom_size(6) | ||
|
||
class_k = Kitchen('kitchen', 'to eat') | ||
print(class_k) | ||
class_k.get_size() | ||
|
||
class_k = Bathroom('bathroom', 'to wash') | ||
print(class_k) | ||
class_k.get_size() | ||
|
||
class_bb = BigBedroom('big bedroom', 'to sleep') | ||
print(class_bb) | ||
|
||
class_gb = GuestBedroom('guest bedroom', 'to sleep') | ||
print(class_gb) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вот так должен выглядеть пример использования наших классов:
# Создаем объект класса Kitchen, передаем ему размер 13
my_kitchen = Kitchen(13)
# Создаем объект класса Bedroom, передаем ему размер 18
my_bedroom = Bedroom(18)
# Создаем объект класса Bathroom, передаем ему размер 4
my_bathroom = Bathroom(4)
# Создаем объект класса Flat, передаем ему созданные выше объекты
my_flat = Flat(my_kitchen, my_bedroom, my_bathroom)
# Обратите внимание, что методы ниже не принимают никаких входных данных,
# так как все эти данные уже хранятся внутри объекта класса Flat (а именно внутри объектов my_kitchen, my_bedroom и my_bathroom, которые мы передали во время создания объекта my_flat)
my_flat.print_rooms()
my_flat.print_flat_size()
my_flat.print_kitchen_size()
my_flat.print_bedroom_size()
my_flat.print_bathroom_size()
task_2_flat
Outdated
|
||
def get_size(self): | ||
user_size = input(f'Enter size of {self.name} ') | ||
print(f'{self.name} is {user_size}(sq.m.)') |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Этот класс пока убираем, пишем код так, как-будто доп заданий 1-2 к задаче не было
task_2_flat
Outdated
class BigBedroom(Room): | ||
|
||
def __str__(self): | ||
return f'{self.name} Спальня с двуспальной кроватью' | ||
|
||
class GuestBedroom(Room): | ||
|
||
def __str__(self): | ||
return f'{self.name} Гостевая спальня' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Эти классы тоже пока убираем
task_2_flat
Outdated
class Kitchen(Room): | ||
pass |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Данный класс реализуем в таком виде:
class Kitchen:
TITLE = 'Kitchen'
def __init__(self, size):
self.__size = size
self.__purpose = 'To eat'
def get_size(self):
return self.__size
На что тут обратить внимание?
- Есть два приватных динамических поля __size и __purpose. Поле __size заполняется значением из параметра.
- Есть одно статическое поле для хранения названия комнаты TITLE. Зачем помещать название комнаты в константу? Чтобы защитить себя от возможных опечаток. И кроме того если необходимо будет делать изменения, то достаточно просто изменить содержимое константы в одном месте, а не делать правки по всей программе.
- Метод get_size() возвращает содержимое приватного поля __size (обратите внимание, что он никуда ничего не печатает)
task_2_flat
Outdated
def print_rooms(self): | ||
print (f'{self.kitchen, self.bedroom, self.bedroom}') | ||
|
||
def print_flat_size(self, kitchen_size, bedroom_size, bathroom_size): | ||
size = self._calculate_flat_size(kitchen_size, bedroom_size, bathroom_size) | ||
print(f'Flat {size}sq.m.') | ||
|
||
def print_kitchen_size(self, size): | ||
print(f'{self.kitchen} {size}sq.m.') | ||
|
||
def print_bedroom_size(self, size): | ||
print(f'{self.bedroom} {size}sq.m.') | ||
|
||
def print_bathroom_size(self, size): | ||
print(f'{self.bathroom} {size}sq.m.') | ||
|
||
def _calculate_flat_size(self, kitchen_size, bedroom_size, bathroom_size): | ||
return f'{kitchen_size + bathroom_size + bedroom_size}' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Эти методы можете пока закомментить - мы к ним вернемся, когда верно реализуем классы Kitchen, Bedroom, Bathroom
task_2_flat
Outdated
class Bedroom(Room): | ||
pass | ||
|
||
class Bathroom(Room): | ||
pass |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Реализуйте данные классы по примеру выше для класса Kitchen
1 Этап.
# print(f'{self.name} is {user_size}(sq.m.)') | ||
|
||
|
||
class Kitchen(Room): |
This comment was marked as outdated.
This comment was marked as outdated.
Sorry, something went wrong.
task_2_flat
Outdated
#def print_rooms(self): | ||
# print (f'{self.kitchen, self.bedroom, self.bedroom}') | ||
|
||
#def print_flat_size(self, kitchen_size, bedroom_size, bathroom_size): | ||
# size = self._calculate_flat_size(kitchen_size, bedroom_size, bathroom_size) | ||
# print(f'Flat {size}sq.m.') | ||
|
||
#def print_kitchen_size(self, size): | ||
# print(f'{self.kitchen} {size}sq.m.') | ||
|
||
#def print_bedroom_size(self, size): | ||
# print(f'{self.bedroom} {size}sq.m.') | ||
|
||
#def print_bathroom_size(self, size): | ||
# print(f'{self.bathroom} {size}sq.m.') | ||
|
||
#def _calculate_flat_size(self, kitchen_size, bedroom_size, bathroom_size): | ||
# return f'{kitchen_size + bathroom_size + bedroom_size}' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Когда закончите с предыдущими двумя комментариями, можно переходить к этапу 4. Реализуем до конца класс Flat, а именно - добавляем все те методы, которые закомментили:
def print_rooms(self):
def print_flat_size(self):
def print_kitchen_size(self):
def print_bedroom_size(self):
def print_bathroom_size(self):
def _calculate_flat_size(self):
На что обратить внимание?
- Еще раз акцентирую внимание - делаем только после того, как сделаем изменения по первым двум пунктам (так как для реализации текущих методов нужен метод get_size() классов Kitchen, Bedroom, Bathroom)
- Методы, которые начинаются с print выводят строки на печать. А метод _calculate_flat_size() возвращает размер квартиры, то есть возвращает число.
- Для получения размеров каждой из комнат используйте соответствующий метод get_size(). Например:
def print_kitchen_size(self):
print(f'Kitchen size: {self.kitchen.get_size()}')
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Плюс добавляем примеры использования свежесозданных методов:
my_kitchen = Kitchen(13)
my_bedroom = Bedroom(18)
my_bathroom = Bathroom(4)
my_flat = Flat(my_kitchen, my_bedroom, my_bathroom)
my_flat.print_rooms()
my_flat.print_flat_size()
my_flat.print_kitchen_size()
my_flat.print_bedroom_size()
my_flat.print_bathroom_size()
task_2_flat
Outdated
def _calculate_flat_size(self, kitchen_size, bedroom_size, bathroom_size): | ||
return f'{self.kitchen.get_size() + self.bathroom.get_size() + self.bedroom.get_size()}' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В чем смысл переданных в метод параметров? Класс Flat хранит внутри себя все три объекта для каждой комнаты:
self.kitchen = kitchen
self.bedroom = bedroom
self.bathroom = bathroom
Поэтому ничего внутрь передавать не надо. Используйте то, что уже есть внутри класса. Собственно именно это вы и делаете
self.kitchen.get_size() + self.bathroom.get_size() + self.bedroom.get_size()
А параметры kitchen_size, bedroom_size, bathroom_size
не нужны
task_2_flat
Outdated
def print_flat_size(self, kitchen_size, bedroom_size, bathroom_size): | ||
flat_size = self._calculate_flat_size(kitchen_size, bedroom_size, bathroom_size) | ||
print(f'Flat size: {flat_size}') |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Аналогично - параметры не нужны
task_2_flat
Outdated
def print_rooms(self): | ||
print(f'{self.kitchen, self.bedroom, self.bedroom}') |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Когда вы передаете на print сами объекты, то на выходе получаете:
(<__main__.Kitchen object at 0x10a6f8490>, <__main__.Bedroom object at 0x10a6f8810>, <__main__.Bedroom object at 0x10a6f8810>)
Это не читабельно. Воспользуйтесь свойством TITLE для каждого объекта, например:
Kitchen.TITLE
self.__purpose = 'To wash' | ||
|
||
|
||
class BigBedroom(Room): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А в чем выгода наличия классов BigBedroom и GuestBedroom, если они наследуются от Room? Ни в чем. Надо наследовать их от класса Bedroom, тогда можно унаследовать например поле __purpose - ведь хоть это разные виды спален, но все равно назначение To sleep не меняется, это все равно спальни.
Плюс каждому из этих классов можно добавить свой функционал. Например, у класса BigBedroom можно не передавать в конструктор размер, а задать его внутри(ведь большой не может считаться спальня с любым размером). Например так:
class BigBedroom(Bedroom):
TITLE = 'BigBedroom'
SIZE = 20
def __init__(self):
super().__init__(SIZE)
No description provided.