-
Notifications
You must be signed in to change notification settings - Fork 0
Home work 06 #7
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
Open
Yuriy-Zhitkov
wants to merge
1
commit into
Yuriy-Zhitkov
Choose a base branch
from
Home_work_06
base: Yuriy-Zhitkov
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Home work 06 #7
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| ''' | ||
| Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод running (запуск). | ||
| Атрибут реализовать как приватный. | ||
|
|
||
| В рамках метода реализовать переключение светофора в режимы: красный, желтый, зеленый. | ||
| Продолжительность первого состояния (красный) составляет 7 секунд, второго (желтый) — 2 секунды, | ||
| третьего (зеленый) — на ваше усмотрение. | ||
|
|
||
| Переключение между режимами должно осуществляться только в указанном порядке (красный, желтый, зеленый). | ||
| Проверить работу примера, создав экземпляр и вызвав описанный метод. | ||
|
|
||
| Задачу можно усложнить, реализовав проверку порядка режимов, и при его нарушении выводить соответствующее | ||
| сообщение и завершать скрипт. | ||
| ''' | ||
|
|
||
| import time | ||
|
|
||
|
|
||
| class TrafficLight: | ||
|
|
||
| def __init__(self): | ||
| self.__color = ['Red', 'Yellow', 'Green'] | ||
|
|
||
|
|
||
| def running(self, times, *time_light): | ||
| ''' | ||
| Метод запуска светофора | ||
| :param times: количество циклов работы светофора | ||
| :param *time_light: длительность (сек) свечения каждым цветом | ||
| :return: выводит на экран сообщение о цвете | ||
| ''' | ||
| n_light = 0 | ||
| for i in range(times * len(self.__color)): | ||
| # вывод на экран информации о цвете световора с определенной длительностью времени | ||
| print(self.__color[n_light]) | ||
| time.sleep(time_light[n_light]) | ||
| # счетчик порядкового номера цвета в светофоре | ||
| n_light += 1 | ||
| if n_light == len(self.__color): | ||
| n_light = 0 | ||
|
|
||
|
|
||
| Light_01 = TrafficLight() | ||
| Light_01.running(3, 7, 2, 3) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| ''' | ||
| Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). | ||
| Значения данных атрибутов должны передаваться при создании экземпляра класса. | ||
| Атрибуты сделать защищенными. | ||
|
|
||
| Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна. | ||
| Использовать формулу: длина * ширина * плотность * число см толщины полотна. Проверить работу метода. | ||
|
|
||
| ''' | ||
|
|
||
|
|
||
| class Road: | ||
|
|
||
| def __init__(self, density, length, width, thickness): | ||
| self.density = density # плотность асфальта, кг/м3 | ||
| self.length = length # длина участка дороги, м | ||
| self.width = width # ширина участка дороги, м | ||
| self.thickness = thickness # толщина дорожного полотна, см | ||
|
|
||
| def mass(self): | ||
| ''' | ||
| Метод определения массы дорожного полотна | ||
| :return: масса, тонны | ||
| ''' | ||
| return (self.length * self.width * self.thickness / 100 * self.density) / 1000 | ||
|
|
||
| road_section_01 = Road(1300, 5000, 20, 5) | ||
| mass_of_road = road_section_01.mass() | ||
| print(mass_of_road) | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| ''' | ||
| Реализовать базовый класс Worker (работник). | ||
| - определить атрибуты: name, surname, position (должность), income (доход); | ||
| - последний атрибут должен быть защищённым и ссылаться на словарь, содержащий | ||
| элементы: оклад и премия, например, {"wage": wage, "bonus": bonus} | ||
|
|
||
| Cоздать класс Position (должность) на базе класса Worker; | ||
| - в классе Position реализовать методы получения полного имени сотрудника | ||
| (get_full_name) и дохода с учётом премии (get_total_income); | ||
| - проверить работу примера на реальных данных: создать экземпляры класса Position, | ||
| передать данные, проверить значения атрибутов, вызвать методы экземпляров. | ||
| ''' | ||
|
|
||
|
|
||
|
|
||
|
|
||
| class Worker: | ||
|
|
||
| def __init__(self, name, surname, position, wage, bonus): | ||
| self.name = name # имя | ||
| self.surname = surname # фамилия | ||
| self.position = position # должность | ||
| self._income = {'wage': wage, 'bonus': bonus} # доход | ||
|
|
||
|
|
||
|
|
||
| class Position(Worker): | ||
|
|
||
| def get_full_name(self): # полное имя сотрудника | ||
| return f'{self.name} {self.surname}' | ||
|
|
||
| def get_total_income(self): # сумма зарплаты и премии | ||
| return self._income['wage'] + self._income['bonus'] | ||
|
|
||
|
|
||
|
|
||
|
|
||
| max = Position('Max', 'Jason', 'Head of department', 7000, 2000) # создаю экземпляр класса | ||
| print(max.__dict__) # проверяю значения атрибутов | ||
|
|
||
| full_name_max = max.get_full_name() # применяю метод для вывода полного имени работника | ||
| print(full_name_max) | ||
|
|
||
| salary_max = max.get_total_income() # применяю метод расчета суммарного дохода | ||
| print(salary_max) | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| ''' | ||
| Реализуйте базовый класс Car: | ||
| - у класса должны быть следующие атрибуты: speed, color, name, is_police (булево). А также методы: go, stop, | ||
| turn(direction), которые должны сообщать, что машина поехала, остановилась, повернула (куда); | ||
| - опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar; | ||
| - добавьте в базовый класс метод show_speed, который должен показывать текущую | ||
| скорость автомобиля; | ||
| - для классов TownCar и WorkCar переопределите метод show_speed. При значении скорости свыше 60 (TownCar) и | ||
| 40 (WorkCar) должно выводиться сообщение о превышении скорости. | ||
|
|
||
| Создайте экземпляры классов, передайте значения атрибутов. Выполните доступ к атрибутам, выведите результат. | ||
| Вызовите методы и покажите результат. | ||
| ''' | ||
|
|
||
| class Car: | ||
|
|
||
| def __init__(self, speed, color, name, is_polise): | ||
| self.speed = speed | ||
| self.color = color | ||
| self.name = name | ||
| self.is_police = is_polise | ||
|
|
||
| def go(self): | ||
| print(f'Автомобиль {self.name} поехал') | ||
|
|
||
| def stop(self): | ||
| print(f'Автомобиль {self.name} остановился') | ||
|
|
||
| def turn(self, direction): | ||
| print(f'Автомобиль {self.name} повернул на {direction}') | ||
|
|
||
| def show_speed(self): | ||
| print(f'У водителя {self.name} текущая скорость {self.speed}') | ||
|
|
||
|
|
||
| class TownCar(Car): | ||
|
|
||
| max_speed = 60 # можно ли по ходу выполнения программы переназначить этот параметр??? | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. TownCar.max_speed = 4242 |
||
|
|
||
| def __init__(self, speed, color, name, is_polise, invalid): | ||
| Car.__init__(self, speed, color, name, is_polise) | ||
| self.invalid = invalid | ||
|
|
||
| def show_speed(self): | ||
| if self.speed <= TownCar.max_speed: | ||
| print(f'У водителя {self.name} текущая скорость {self.speed}') | ||
| else: | ||
| print(f'У водителя {self.name} превышение скорости!!! Допустимая скорость {TownCar.max_speed}') | ||
|
|
||
|
|
||
| class WorkCar(Car): | ||
|
|
||
| max_speed = 40 | ||
|
|
||
| def __init__(self, speed, color, name, is_polise, loaded): | ||
| Car.__init__(self, speed, color, name, is_polise) | ||
| self.loaded = loaded | ||
|
|
||
| def show_speed(self): | ||
| if self.speed <= WorkCar.max_speed: | ||
| print(f'У водителя {self.name} текущая скорость {self.speed}') | ||
| else: | ||
| print(f'У водителя {self.name} превышение скорости!!! Допустимая скорость {WorkCar.max_speed}') | ||
|
|
||
|
|
||
| class SportCar(Car): | ||
|
|
||
| def __init__(self, speed, color, name, is_polise, brand): | ||
| Car.__init__(self, speed, color, name, is_polise) | ||
| self.brand = brand | ||
|
|
||
|
|
||
| class PoliseCar(Car): | ||
|
|
||
| def __init__(self, speed, color, name, is_polise, on_line): | ||
| Car.__init__(self, speed, color, name, is_polise) | ||
| self.on_line = on_line | ||
|
|
||
| def signal(self): | ||
| print(f'Полицейская машина {self.name} включила проблесковые маячки') | ||
|
|
||
|
|
||
| max_car = TownCar(40, 'yellow', 'Max', False, False) | ||
| kate_car = WorkCar(60, 'yellow', 'Kate', False, False) | ||
| jack_car = SportCar(120, 'yellow', 'Jack', False, 'BMW') | ||
| tom_car = PoliseCar(40, 'yellow', 'Tom', True, False) | ||
|
|
||
| print(max_car.__dict__) | ||
| print(kate_car.__dict__) | ||
| print(jack_car.__dict__) | ||
| print(tom_car.__dict__) | ||
|
|
||
| print('-' * 100) | ||
|
|
||
| max_car.go(), kate_car.go(), jack_car.go() | ||
| max_car.show_speed(), kate_car.show_speed(), jack_car.show_speed() | ||
| tom_car.go(), tom_car.signal() | ||
| kate_car.turn('Left'), jack_car.turn('Left'), tom_car.turn('Left') | ||
| kate_car.stop(), jack_car.stop(), tom_car.stop() | ||
|
|
||
|
|
||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| ''' | ||
| Реализовать класс Stationery (канцелярская принадлежность). | ||
| - определить в нём атрибут title (название) и метод draw (отрисовка). Метод выводит сообщение «Запуск отрисовки»; | ||
| - создать три дочерних класса Pen (ручка), Pencil (карандаш), Handle (маркер); | ||
| - в каждом классе реализовать переопределение метода draw. Для каждого класса | ||
| метод должен выводить уникальное сообщение; | ||
| - создать экземпляры классов и проверить, что выведет описанный метод для каждого | ||
| экземпляра. | ||
| ''' | ||
|
|
||
| class Stationery(): | ||
|
|
||
| def __init__(self, title): | ||
| self.title = title | ||
|
|
||
| def draw(self): | ||
| print('Запуск отрисовки') | ||
|
|
||
|
|
||
| class Pen(Stationery): | ||
|
|
||
| def draw(self): | ||
| print('Запуск отрисовки ручкой') | ||
|
|
||
|
|
||
| class Pencil(Stationery): | ||
|
|
||
| def draw(self): | ||
| print('Запуск отрисовки карандашом') | ||
|
|
||
|
|
||
| class Handle(Stationery): | ||
|
|
||
| def draw(self): | ||
| print('Запуск отрисовки маркером') | ||
|
|
||
|
|
||
| my_pen = Pen('Red color pen') | ||
| my_pencil = Pencil('Sample pencil') | ||
| my_handle = Handle('Greed handle') | ||
|
|
||
| my_pen.draw() | ||
| my_pencil.draw() | ||
| my_handle.draw() | ||
|
|
||
|
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
названия объектов не пишут с заглавной буквы