-
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 all 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,45 @@ | ||
# 1. Реализовать класс «Дата», функция-конструктор которого должна принимать | ||
# дату в виде строки формата «день-месяц-год». В рамках класса реализовать два метода. | ||
# Первый, с декоратором @classmethod, должен извлекать число, месяц, | ||
# год и преобразовывать их тип к типу «Число». Второй, с декоратором @staticmethod, | ||
# должен проводить валидацию числа, месяца и года (например, месяц — от 1 до 12). | ||
# Проверить работу полученной структуры на реальных данных. | ||
|
||
class Data: | ||
def __init__(self, day_month_year): | ||
self.day_month_year = str(day_month_year) | ||
|
||
@classmethod | ||
def extract(cls, day_month_year): | ||
my_date = [] | ||
|
||
for i in day_month_year.split(): | ||
if i != '-': my_date.append(i) | ||
|
||
return int(my_date[0]), int(my_date[1]), int(my_date[2]) | ||
|
||
@staticmethod | ||
def valid(day, month, year): | ||
|
||
if 1 <= day <= 31: | ||
if 1 <= month <= 12: | ||
if 2019 >= year >= 0: | ||
return f'All right' | ||
else: | ||
return f'Неправильный год' | ||
else: | ||
return f'Неправильный месяц' | ||
else: | ||
return f'Неправильный день' | ||
|
||
def __str__(self): | ||
return f'Текущая дата {Data.extract(self.day_month_year)}' | ||
|
||
|
||
today = Data('11 - 1 - 2001') | ||
print(today) | ||
print(Data.valid(11, 11, 2022)) | ||
print(today.valid(11, 13, 2011)) | ||
print(Data.extract('11 - 11 - 2011')) | ||
print(today.extract('11 - 11 - 2020')) | ||
print(Data.valid(1, 11, 2000)) | ||
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
# 2. Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. | ||
# Проверьте его работу на данных, вводимых пользователем. При вводе пользователем | ||
# нуля в качестве делителя программа должна корректно обработать эту ситуацию и | ||
# не завершиться с ошибкой. | ||
|
||
|
||
class DivisionByNull: | ||
def __init__(self, divider, denominator): | ||
self.divider = divider | ||
self.denominator = denominator | ||
|
||
@staticmethod | ||
def divide_by_null(divider, denominator): | ||
try: | ||
return (divider / denominator) | ||
except: | ||
return (f"Деление на ноль недопустимо") | ||
|
||
|
||
div = DivisionByNull(10, 100) | ||
print(DivisionByNull.divide_by_null(10, 0)) | ||
print(DivisionByNull.divide_by_null(10, 0.1)) | ||
print(div.divide_by_null(100, 0)) | ||
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,31 @@ | ||
# 3. Создайте собственный класс-исключение, который должен проверять содержимое списка | ||
# на отсутствие элементов типа строка и булево. Проверить работу исключения на реальном примере. | ||
# Необходимо запрашивать у пользователя данные и заполнять список. | ||
# Класс-исключение должен контролировать типы данных элементов списка. | ||
|
||
|
||
class Error: | ||
def __init__(self, *args): | ||
self.my_list = [] | ||
|
||
def my_input(self): | ||
|
||
|
||
while True: | ||
try: | ||
val = int(input('Введите значения и нажимайте Enter - ')) | ||
self.my_list.append(val) | ||
print(f'Текущий список - {self.my_list} \n ') | ||
except: | ||
print(f"Недопустимое значение - строка и булево") | ||
y_or_n = input(f'Попробовать еще раз? Y/N ') | ||
|
||
if y_or_n == 'Y' or y_or_n == 'y': | ||
print(try_except.my_input()) | ||
elif y_or_n == 'N' or y_or_n == 'n': | ||
return f'Вы вышли' | ||
else: | ||
return f'Вы вышли' | ||
|
||
try_except = Error(1) | ||
print(try_except.my_input()) | ||
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,55 @@ | ||
# 4. Начните работу над проектом «Склад оргтехники». Создайте класс, описывающий склад. | ||
# А также класс «Оргтехника», который будет базовым для классов-наследников. | ||
# Эти классы — конкретные типы оргтехники (принтер, сканер, ксерокс). | ||
# В базовом классе определить параметры, общие для приведенных типов. | ||
# В классах-наследниках реализовать параметры, уникальные для каждого типа оргтехники. | ||
|
||
class Sklad: | ||
def __init__(self): | ||
self._dict = {} | ||
|
||
|
||
class Equipment: | ||
def __init__(self, name, make, year): | ||
self.name = name | ||
self.make = make | ||
self.year = year | ||
self.group = self.__class__.__name__ | ||
|
||
def group_name(self): | ||
return f'{self.group}' | ||
|
||
def __repr__(self): | ||
return f'{self.name} {self.make} {self.year}' | ||
|
||
|
||
class Printer(Equipment): | ||
def __init__(self, series, name, make, year): | ||
super().__init__(name, make, year) | ||
self.series = series | ||
|
||
def __repr__(self): | ||
return f'{self.name} {self.series} {self.make} {self.year}' | ||
|
||
def action(self): | ||
return 'Печатает' | ||
|
||
|
||
class Scaner(Equipment): | ||
def __init__(self, name, make, year): | ||
super().__init__(name, make, year) | ||
|
||
def action(self): | ||
return 'Сканирует' | ||
|
||
|
||
class Xerox(Sklad): | ||
def __init__(self, name, make, year): | ||
super().__init__(name, make, year) | ||
|
||
def action(self): | ||
return 'Копирует' | ||
|
||
|
||
sklad = Sklad() | ||
print(sklad.__dict__) | ||
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. Sklad |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
# 5. Продолжить работу над первым заданием. Разработать методы, отвечающие за приём оргтехники | ||
# на склад и передачу в определенное подразделение компании. Для хранения данных | ||
# о наименовании и количестве единиц оргтехники, а также других данных, можно использовать | ||
# любую подходящую структуру (например словарь). | ||
|
||
class Sklad: | ||
def __init__(self): | ||
self._dict = {} | ||
|
||
def add_to(self, equipment): | ||
self._dict.setdefault(equipment.group_name(), []).append(equipment) | ||
|
||
def extract(self, name): | ||
if self._dict[name]: | ||
self._dict.setdefault(name).pop(0) | ||
|
||
|
||
class Equipment: | ||
def __init__(self, name, make, year): | ||
self.name = name | ||
self.make = make | ||
self.year = year | ||
self.group = self.__class__.__name__ | ||
|
||
def group_name(self): | ||
return f'{self.group}' | ||
|
||
def __repr__(self): | ||
return f'{self.name} {self.make} {self.year}' | ||
|
||
|
||
class Printer(Equipment): | ||
def __init__(self, series, name, make, year): | ||
super().__init__(name, make, year) | ||
self.series = series | ||
|
||
def __repr__(self): | ||
return f'{self.name} {self.series} {self.make} {self.year}' | ||
|
||
def action(self): | ||
return 'Печатает' | ||
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,67 @@ | ||
# 6. Продолжить работу над вторым заданием. Реализуйте механизм валидации вводимых | ||
# пользователем данных. Например, для указания количества принтеров, отправленных | ||
# на склад, нельзя использовать строковый тип данных. | ||
# Подсказка: постарайтесь по возможности реализовать в проекте «Склад оргтехники» | ||
# максимум возможностей, изученных на уроках по ООП. | ||
|
||
|
||
class StoreMashines: | ||
|
||
def __init__(self, name, price, quantity, number_of_lists, *args): | ||
self.name = name | ||
self.price = price | ||
self.quantity = quantity | ||
self.numb = number_of_lists | ||
self.my_store_full = [] | ||
self.my_store = [] | ||
self.my_unit = {'Модель устройства': self.name, 'Цена за ед': self.price, 'Количество': self.quantity} | ||
|
||
def __str__(self): | ||
return f'{self.name} цена {self.price} количество {self.quantity}' | ||
|
||
|
||
def reception(self): | ||
try: | ||
unit = input(f'Введите наименование ') | ||
unit_p = int(input(f'Введите цену за ед ')) | ||
unit_q = int(input(f'Введите количество ')) | ||
unique = {'Модель устройства': unit, 'Цена за ед': unit_p, 'Количество': unit_q} | ||
self.my_unit.update(unique) | ||
self.my_store.append(self.my_unit) | ||
print(f'Текущий список -\n {self.my_store}') | ||
except: | ||
return f'Ошибка ввода данных' | ||
|
||
print(f'Для выхода - Q, продолжение - Enter') | ||
q = input(f'---> ') | ||
if q == 'Q' or q == 'q': | ||
self.my_store_full.append(self.my_store) | ||
print(f'Весь склад -\n {self.my_store_full}') | ||
return f'Выход' | ||
else: | ||
return StoreMashines.reception(self) | ||
|
||
|
||
class Printer(StoreMashines): | ||
def to_print(self): | ||
return f'to print smth {self.numb} times' | ||
|
||
|
||
class Scanner(StoreMashines): | ||
def to_scan(self): | ||
return f'to scan smth {self.numb} times' | ||
|
||
|
||
class Copier(StoreMashines): | ||
def to_copier(self): | ||
return f'to copier smth {self.numb} times' | ||
|
||
|
||
unit_1 = Printer('hp', 2000, 5, 10) | ||
unit_2 = Scanner('Canon', 1200, 5, 10) | ||
unit_3 = Copier('Xerox', 1500, 1, 15) | ||
print(unit_1.reception()) | ||
print(unit_2.reception()) | ||
print(unit_3.reception()) | ||
print(unit_1.to_print()) | ||
print(unit_3.to_copier()) | ||
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,31 @@ | ||
# 7. Реализовать проект «Операции с комплексными числами». Создайте класс «Комплексное число», | ||
# реализуйте перегрузку методов сложения и умножения комплексных чисел. | ||
# Проверьте работу проекта, создав экземпляры класса (комплексные числа) и | ||
# выполнив сложение и умножение созданных экземпляров. | ||
# Проверьте корректность полученного результата. | ||
|
||
|
||
|
||
class ComplexNumber: | ||
def __init__(self, a, b, *args): | ||
self.a = a | ||
self.b = b | ||
self.z = 'a + b * i' | ||
|
||
def __add__(self, other): | ||
print(f'Сумма z1 и z2 равна') | ||
return f'z = {self.a + other.a} + {self.b + other.b} * i' | ||
|
||
def __mul__(self, other): | ||
print(f'Произведение z1 и z2 равно') | ||
return f'z = {self.a * other.a - (self.b * other.b)} + {self.b * other.a} * i' | ||
|
||
def __str__(self): | ||
return f'z = {self.a} + {self.b} * i' | ||
|
||
|
||
z_1 = ComplexNumber(1, -2) | ||
z_2 = ComplexNumber(3, 4) | ||
print(z_1) | ||
print(z_1 + z_2) | ||
print(z_1 * z_2) | ||
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.
выполнено