-
Notifications
You must be signed in to change notification settings - Fork 0
Lesson7 #6
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
sofo4ka
wants to merge
8
commits into
master
Choose a base branch
from
lesson7
base: master
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
Lesson7 #6
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
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,42 @@ | ||
| # 1. Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод running (запуск). | ||
| # Атрибут реализовать как приватный. В рамках метода реализовать переключение светофора в режимы: красный, желтый, | ||
| # зеленый. Продолжительность первого состояния (красный) составляет 7 секунд, второго (желтый) — 2 секунды, третьего | ||
| # (зеленый) — на ваше усмотрение. Переключение между режимами должно осуществляться только в указанном порядке | ||
| # (красный, желтый, зеленый). Проверить работу примера, создав экземпляр и вызвав описанный метод. | ||
| # Задачу можно усложнить, реализовав проверку порядка режимов, и при его нарушении выводить соответствующее | ||
| # сообщение и завершать скрипт. | ||
|
|
||
| from time import sleep | ||
|
|
||
|
|
||
| class TrafficLight: | ||
| __color = [('красный', 7), ('желтый', 2), ('зеленый', 6)] | ||
|
|
||
| def checkout_data(self): | ||
| """ проверка данных и порядка смены цветов""" | ||
| colors = ['красный', 'желтый', 'зеленый'] | ||
| for element in self.__color: | ||
| if element[0] not in colors: | ||
| print('Некорректные цвета') | ||
| elif self.__color[0][0] != colors[0] or self.__color[1][0] != colors[1] or self.__color[2][0] != colors[2]: | ||
| print('Задан неправильный порядок смены цветов') | ||
| elif self.__color[0][1] != 7 or self.__color[1][1] != 2: | ||
| print('Некорректное время ожидания') | ||
|
|
||
| def changing_colors(self): | ||
| for color in self.__color: | ||
| print(color[0]) | ||
| sleep(color[1]) | ||
|
|
||
| def running(self): | ||
| n = 3 | ||
| self.checkout_data() | ||
| i = 0 | ||
| while i < n: | ||
| self.changing_colors() | ||
| i += 1 | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| t = TrafficLight() | ||
| t.running() |
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,25 @@ | ||
| # 2. Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). Значения данных | ||
| # атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. Определить метод расчета | ||
| # массы асфальта, необходимого для покрытия всего дорожного полотна. Использовать формулу: | ||
| # длина * ширина * масса асфальта для покрытия одного кв метра дороги асфальтом, толщиной в 1 см * число см | ||
| # толщины полотна. Проверить работу метода. | ||
| # Например: 20м * 5000м * 25кг * 5см = 12500 т | ||
|
|
||
| class Road: | ||
| _mass_for_one_m2 = 25 | ||
| _thickness = 5 | ||
|
|
||
| def __init__(self, length, width): | ||
| self._length = length | ||
| self._width = width | ||
|
|
||
| def mass_calculation(self): | ||
| """Расчет массы асфальта, необходимого для покрытия всего дорожного полотна. Формула: | ||
| длина * ширина * (масса асфальта для покрытия 1 м2 дороги асфальтом, толщиной в 1 см) * толщина в см""" | ||
| full_mass = self._length * self._width * self._mass_for_one_m2 * self._thickness | ||
| return f'Масса асфальта в тоннах: {full_mass/1000}' | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| r = Road(length=5000, width=20) | ||
| print(r.mass_calculation()) |
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,35 @@ | ||
| # 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, income): | ||
| self.name = name | ||
| self.surname = surname | ||
| self.position = position | ||
| self._income = income | ||
|
|
||
|
|
||
| class Position(Worker): | ||
|
|
||
| def __init__(self, name, surname, position, income): | ||
| super().__init__(name, surname, position, income) | ||
| self._full_income_value = self._income.get('wage') + self._income.get('bonus') | ||
|
|
||
| def get_full_name(self): | ||
| """Метод получения полного имени сотрудника""" | ||
| return f'Полное имя: {self.name} {self.surname}' | ||
|
|
||
| def get_total_income(self): | ||
| """Метод получения дохода с учетом премии""" | ||
| return f'Доход с учетом премии: {self._full_income_value} руб.' | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| income_ivanov = {'wage': 100000, 'bonus': 20000} | ||
| p = Position(name='Иван', surname='Иванов', position='пилот', income=income_ivanov) | ||
| print(p.get_full_name()) | ||
| print(p.get_total_income()) |
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,79 @@ | ||
| # 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, name, speed, color, is_police): | ||
| self.name = name | ||
| self.speed = speed | ||
| self.color = color | ||
| self.is_police = is_police | ||
|
|
||
| def show_speed(self): | ||
| print(f'Текущая скорость автомобиля: {self.speed}') | ||
|
|
||
| def go(self): | ||
| print('машина поехала') | ||
|
|
||
| def stop(self): | ||
| print('машина остановилась') | ||
|
|
||
| def turn_direction(self): | ||
| print('машина повернула') | ||
|
|
||
|
|
||
| class TownCar(Car): | ||
| def __init__(self, name, speed, color, is_police): | ||
| super().__init__(name, speed, color, is_police) | ||
|
|
||
| def show_speed(self): | ||
| if self.speed <= 60: | ||
| print(f'Текущая скорость автомобиля: {self.speed}') | ||
| else: | ||
| print(f'Превышение установленной скорости движения транспортного средства, равной 60 км/ч!!!' \ | ||
| f'Текущая скорость автомобиля: {self.speed}') | ||
|
|
||
|
|
||
| class SportCar(Car): | ||
| def __init__(self, name, speed, color, is_police): | ||
| super().__init__(name, speed, color, is_police) | ||
|
|
||
|
|
||
| class WorkCar(Car): | ||
| def __init__(self, name, speed, color, is_police): | ||
| super().__init__(name, speed, color, is_police) | ||
|
|
||
| def show_speed(self): | ||
| if self.speed <= 40: | ||
| print(f'Текущая скорость автомобиля: {self.speed}') | ||
| else: | ||
| print(f'Превышение установленной скорости движения транспортного средства, равной 40 км/ч!!!' \ | ||
| f'Текущая скорость автомобиля: {self.speed}') | ||
|
|
||
|
|
||
| class PoliceCar(Car): | ||
| def __init__(self, name, speed, color, is_police): | ||
| super().__init__(name, speed, color, is_police) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| t = TownCar(speed=48, color='green', name='УАЗ-3303', is_police=False) | ||
| s = SportCar(speed=180, color='red', name='Ferrari 488', is_police=False) | ||
| w = WorkCar(speed=50, color='black', name='ВАЗ-2109', is_police=False) | ||
| p = PoliceCar(speed=80, color='white', name='UAZ Patriot', is_police=True) | ||
|
|
||
| print(t.__dict__) | ||
| print(s.__dict__) | ||
| print(w.__dict__) | ||
| print(p.__dict__) | ||
|
|
||
| t.show_speed() | ||
| s.go() | ||
| w.show_speed() | ||
| p.turn_direction() | ||
| p.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 @@ | ||
| # 5. Реализовать класс Stationery (канцелярская принадлежность). Определить в нем атрибут title (название) и | ||
| # метод draw (отрисовка). Метод выводит сообщение “Запуск отрисовки.” Создать три дочерних класса Pen (ручка), | ||
| # Pencil (карандаш), Handle (маркер). В каждом из классов реализовать переопределение метода draw. Для каждого из | ||
| # классов методы должен выводить уникальное сообщение. Создать экземпляры классов и проверить, что выведет описанный | ||
| # метод для каждого экземпляра. | ||
|
|
||
| class Stationery: | ||
| def __init__(self, title): | ||
| self.title = title | ||
|
|
||
| def draw(self): | ||
| print('Запуск отрисовки.') | ||
|
|
||
|
|
||
| class Pen(Stationery): | ||
| def __init__(self, title): | ||
| super().__init__(title) | ||
|
|
||
| def draw(self): | ||
| print('Запуск отрисовки ручкой.') | ||
|
|
||
|
|
||
| class Pensil(Stationery): | ||
| def __init__(self, title): | ||
| super().__init__(title) | ||
|
|
||
| def draw(self): | ||
| print('Запуск отрисовки карандашом.') | ||
|
|
||
|
|
||
| class Handle(Stationery): | ||
| def __init__(self, title): | ||
| super().__init__(title) | ||
|
|
||
| def draw(self): | ||
| print('Запуск отрисовки маркером.') | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| pen = Pen('black') | ||
| pensil = Pensil('blue') | ||
| handle = Handle('red') | ||
|
|
||
| pen.draw() | ||
| pensil.draw() | ||
| handle.draw() |
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,42 @@ | ||
| # 1. Реализовать класс Matrix (матрица). Обеспечить перегрузку конструктора класса (метод __init__()), который должен | ||
| # принимать данные (список списков) для формирования матрицы. | ||
| # Подсказка: матрица — система некоторых математических величин, расположенных в виде прямоугольной схемы. | ||
| # Примеры матриц вы найдете в методичке. | ||
| # Следующий шаг — реализовать перегрузку метода __str__() для вывода матрицы в привычном виде. | ||
| # Далее реализовать перегрузку метода __add__() для реализации операции сложения двух объектов класса Matrix | ||
| # (двух матриц). Результатом сложения должна быть новая матрица. | ||
| # Подсказка: сложение элементов матриц выполнять поэлементно — первый элемент первой строки первой матрицы складываем | ||
| # с первым элементом первой строки второй матрицы и т.д. | ||
| from random import randint | ||
|
|
||
|
|
||
| class Matrix: | ||
| def __init__(self, spisok_spiskov): | ||
| self.spisok_spiskov = spisok_spiskov | ||
|
|
||
| def __str__(self): | ||
| return str('\n'.join(['\t'.join([str(i) for i in j]) for j in self.spisok_spiskov])) | ||
|
|
||
| def __add__(self, other): | ||
| result_matrix = [] | ||
| for i in range(len(self.spisok_spiskov)): | ||
| result_line = [] | ||
| for j in range(len(self.spisok_spiskov[0])): | ||
| result_line.append(int(self.spisok_spiskov[i][j]) + int(other.spisok_spiskov[i][j])) | ||
| result_matrix.append(result_line) | ||
| return Matrix(result_matrix) | ||
|
|
||
|
|
||
| m = [[randint(-50, 50) for i in range(3)] for j in range(3)] | ||
| m2 = [[randint(-50, 50) for i in range(3)] for j in range(3)] | ||
| m3 = [[randint(-50, 50) for i in range(3)] for j in range(3)] | ||
| test_matrix = Matrix(m) | ||
| test_matrix2 = Matrix(m2) | ||
| test_matrix3 = Matrix(m3) | ||
| print(test_matrix.__str__()) | ||
| print(' ') | ||
| print(test_matrix2.__str__()) | ||
| print(' ') | ||
| print(test_matrix3.__str__()) | ||
| print(' ') | ||
| print(test_matrix + test_matrix2 + test_matrix3) | ||
|
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. Пора учиться писать тесты) - https://www.youtube.com/watch?v=1HtEPEn4-LY&t=306s&ab_channel=Luchanos |
||
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 @@ | ||
| # 2. Реализовать проект расчета суммарного расхода ткани на производство одежды. Основная сущность (класс) этого | ||
| # проекта — одежда, которая может иметь определенное название. К типам одежды в этом проекте относятся пальто и костюм. | ||
| # У этих типов одежды существуют параметры: размер (для пальто) и рост (для костюма). Это могут быть обычные числа: | ||
| # V и H, соответственно. | ||
| # Для определения расхода ткани по каждому типу одежды использовать формулы: для пальто (V/6.5 + 0.5), для костюма | ||
| # (2 * H + 0.3). Проверить работу этих методов на реальных данных. | ||
| # Реализовать общий подсчет расхода ткани. Проверить на практике полученные на этом уроке знания: реализовать | ||
| # абстрактные классы для основных классов проекта, проверить на практике работу декоратора @property. | ||
|
|
||
| from abc import abstractmethod, ABC | ||
|
|
||
|
|
||
| class Clothes(ABC): | ||
| def __init__(self, name): | ||
| self.name = name | ||
|
|
||
| @property | ||
| @abstractmethod | ||
| def fabric_consumption_calc(self): | ||
| pass | ||
|
|
||
|
|
||
| class Coat(Clothes): | ||
| def __init__(self, name, size): | ||
| super(Coat, self).__init__(name) | ||
| self.size = size | ||
|
|
||
|
|
||
| def fabric_consumption_calc(self): | ||
| return round(self.size / 6.5 + 0.5, 2) | ||
|
|
||
|
|
||
| class Suit(Clothes): | ||
| def __init__(self, name, height): | ||
| super(Suit, self).__init__(name) | ||
| self.height = height | ||
|
|
||
| def fabric_consumption_calc(self): | ||
| return round(2 * self.height + 0.3, 2) | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| c = Coat('красное пальто', size=42) | ||
| s = Suit('чёрный костюм', 170) | ||
| print(c.fabric_consumption_calc()) | ||
| print(s.fabric_consumption_calc()) |
Oops, something went wrong.
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.
magic методы не должны вызываться напрямую!_)