-
Notifications
You must be signed in to change notification settings - Fork 73
Practical work 3 Pogorely_E_P #133
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
base: master
Are you sure you want to change the base?
Changes from 40 commits
16d6e67
3a32f48
babb021
13f9556
cd586db
cac1425
4124c0e
98980b1
b173d00
55b912b
203d39f
6ffa361
8c7f74d
fa4a73c
1a74dae
56a112e
6a15565
37852ee
d984c17
f3ee376
307bea5
7563fec
77f1868
fa49010
f03e726
91c4d1c
b0f4953
03dbe20
2459f00
6ec341a
13490ad
cd6e9b0
52539fd
af888a8
e4812f6
9a605ab
661408b
44cdd5e
3a69e72
b0efbf8
bff2bd0
0c8864b
10e0d38
92e5ee1
815dbcd
6ea7028
92f8ea5
88c059b
17e9197
a903767
8c09661
146cfe4
6c65765
f729457
1ddac2a
31e3768
4bd25a9
ec9cefd
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| # 1. Создать класс TrafficLight (светофор). | ||
| # определить у него один атрибут color (цвет) и метод running (запуск); | ||
| # атрибут реализовать как приватный; | ||
| # в рамках метода реализовать переключение светофора в режимы: красный, жёлтый, зелёный; | ||
| # продолжительность первого состояния (красный) составляет 7 секунд, второго | ||
| # (жёлтый) — 2 секунды, третьего (зелёный) — на ваше усмотрение; | ||
| # переключение между режимами должно осуществляться только в указанном порядке (красный, жёлтый, зелёный); | ||
| # проверить работу примера, создав экземпляр и вызвав описанный метод. | ||
| # Задачу можно усложнить, реализовав проверку порядка режимов. | ||
| # При его нарушении выводить соответствующее сообщение и завершать скрипт. | ||
|
|
||
| import time | ||
| class TrafficLight: | ||
| __color = ['Красный', 'Желтый', 'Зеленый'] | ||
|
|
||
| def running(self): | ||
| for i in range(3): | ||
| print(f'Светофор горит: {TrafficLight.__color[i]}') | ||
| if TrafficLight.__color[i] == 'Красный': | ||
| time.sleep(7) | ||
| elif TrafficLight.__color[i] == 'Желтый': | ||
| time.sleep(2) | ||
| elif TrafficLight.__color[i] == 'Зеленный': | ||
| time.sleep(5) | ||
|
|
||
| a = TrafficLight() | ||
| a.running() | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| # 2. Реализовать класс Road (дорога). | ||
| # определить атрибуты: length (длина), width (ширина); | ||
| # значения атрибутов должны передаваться при создании экземпляра класса; | ||
| # атрибуты сделать защищёнными; | ||
| # определить метод расчёта массы асфальта, необходимого для покрытия всей дороги; | ||
| # использовать формулу: длина*ширина*масса асфальта для покрытия одного кв. метра дороги асфальтом, | ||
| # толщиной в 1 см*число см толщины полотна; | ||
| # проверить работу метода. | ||
| # Например: 20 м*5000 м*25 кг*5 см = 12500 т. | ||
|
|
||
| class Road: | ||
| def __init__(self, _length, _width): | ||
| self._length = _length | ||
| self._width = _width | ||
|
|
||
| def mass(self): | ||
| self.weight = 25 | ||
| self.thickness = 0.05 | ||
| return self._length * self._width * self.weight * self.thickness | ||
|
|
||
|
|
||
| r = Road(20, 5000) | ||
|
|
||
| print(r.mass()) | ||
|
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. выполнено |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| # 3. Реализовать базовый класс Worker (работник). | ||
| # определить атрибуты: name, surname, position (должность), income (доход); | ||
| # последний атрибут должен быть защищённым и ссылаться на словарь, содержащий элементы: | ||
| # оклад и премия, например, {"wage": wage, "bonus": bonus}; | ||
| # создать класс 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 __init__(self, name, surname, position, wage, bonus): | ||
| super().__init__(name, surname, position, wage, bonus) | ||
|
|
||
| def get_full_name(self): | ||
| return f'{self.name} {self.surname}' | ||
|
|
||
| def get_total_income(self): | ||
| return self._income.get('wage') + self._income.get('bonus') | ||
|
|
||
|
|
||
|
|
||
| res = Position('Иван', 'Петров', 'Грузчик', 50000, 3000) | ||
| print(res.get_full_name()) | ||
| print(res.position) | ||
| print(res.get_total_income()) | ||
|
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. выполнено |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| # 4. Реализуйте базовый класс 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_police): | ||
| self.speed = speed | ||
| self.color = color | ||
| self.name = name | ||
| self.is_police = is_police | ||
|
|
||
| def go(self): | ||
| return f'{self.name} едет' | ||
|
|
||
| def stop(self): | ||
| return f'{self.name} остановился' | ||
|
|
||
| def turn_right(self): | ||
| return f'{self.name} перевернулся в право' | ||
|
|
||
| def turn_left(self): | ||
| return f'{self.name} перевернулся в лево' | ||
|
|
||
| def show_speed(self): | ||
| return f'Скорость {self.name} равна {self.speed}' | ||
|
|
||
|
|
||
| class TownCar(Car): | ||
| def __init__(self, speed, color, name, is_police): | ||
| super().__init__(speed, color, name, is_police) | ||
|
|
||
| def show_speed(self): | ||
| print(f'Скорость городского автомобиля {self.name} равна {self.speed}') | ||
|
|
||
| if self.speed > 40: | ||
| return f' {self.name} привысил скорость' | ||
| else: | ||
| return f'{self.name} без привышения скорости' | ||
|
|
||
| class SportCar(Car): | ||
| def __init__(self, speed, color, name, is_police): | ||
| super().__init__(speed, color, name, is_police) | ||
|
|
||
|
|
||
| class WorkCar(Car): | ||
| def __init__(self, speed, color, name, is_police): | ||
| super().__init__(speed, color, name, is_police) | ||
|
|
||
| def show_speed(self): | ||
| print(f'Скорость рабочего автомобиля {self.name} равна {self.speed}') | ||
|
|
||
| if self.speed > 60: | ||
| return f'Скорость {self.name} превышена' | ||
|
|
||
|
|
||
| class PoliceCar(Car): | ||
| def __init__(self, speed, color, name, is_police): | ||
| super().__init__(speed, color, name, is_police) | ||
|
|
||
| def police(self): | ||
| if self.is_police: | ||
| return f'{self.name} полицейская машина' | ||
| else: | ||
| return f'{self.name} полицейская машина' | ||
|
|
||
|
|
||
| gaz = SportCar(100, 'красный', 'ГАЗ', False) | ||
| zaz = TownCar(30, 'белый', 'ЗАЗ', False) | ||
| lada = WorkCar(70, 'желтый', 'Лада', True) | ||
| uaz = PoliceCar(110, 'синий', 'Ford', True) | ||
| print(lada.turn_left()) | ||
| print(f'Когда {zaz.turn_right()}, тогда {gaz.stop()}') | ||
| print(f'{lada.go()} со скоростью {lada.show_speed()}') | ||
| print(f'{lada.name} имеет цвет {lada.color}') | ||
| print(f'{gaz.name} полицейский автомобиль? {gaz.is_police}') | ||
| print(f'{lada.name} полицейский автомобиль? {lada.is_police}') | ||
| print(gaz.show_speed()) | ||
| print(zaz.show_speed()) | ||
| print(uaz.police()) | ||
| print(uaz.show_speed()) | ||
|
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. выполнено |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| # 5. Реализовать класс Stationery (канцелярская принадлежность). | ||
| # определить в нём атрибут title (название) и метод draw (отрисовка). | ||
| # Метод выводит сообщение «Запуск отрисовки»; | ||
| # создать три дочерних класса Pen (ручка), Pencil (карандаш), Handle (маркер); | ||
| # в каждом классе реализовать переопределение метода draw. Для каждого класса | ||
| # метод должен выводить уникальное сообщение; | ||
| # создать экземпляры классов и проверить, что выведет описанный метод для каждого экземпляра. | ||
|
|
||
| class Stationary: | ||
| def __init__(self, title): | ||
| self.title = title | ||
|
|
||
| def draw(self): | ||
| return f'Запуск отрисовки {self.title}' | ||
|
|
||
|
|
||
| class Pen(Stationary): | ||
| def __init__(self, title): | ||
| super().__init__(title) | ||
|
|
||
| def draw(self): | ||
| return f'Вы взяли {self.title}. Запуск отрисовки ручкой' | ||
|
|
||
|
|
||
| class Pencil(Stationary): | ||
| def __init__(self, title): | ||
| super().__init__(title) | ||
|
|
||
| def draw(self): | ||
| return f'Вы взяли {self.title}. Запуск отрисовки карандашом' | ||
|
|
||
|
|
||
| class Handle(Stationary): | ||
| def __init__(self, title): | ||
| super().__init__(title) | ||
|
|
||
| def draw(self): | ||
| return f'Вы взяли {self.title}. Запуск отрисовки маркером' | ||
|
|
||
|
|
||
| pen = Pen('Ручка') | ||
| pencil = Pencil('Карандаш') | ||
| handle = Handle('Маркер') | ||
| print(pen.draw()) | ||
| print(pencil.draw()) | ||
| print(handle.draw()) | ||
|
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. выполнено |
||
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.
выполнено