Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions Lesson_8/task_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Реализовать класс «Дата», функция-конструктор которого должна принимать дату в виде строки формата «день-месяц-год».
# В рамках класса реализовать два метода. Первый, с декоратором @classmethod.
# Он должен извлекать число, месяц, год и преобразовывать их тип к типу «Число».
# Второй, с декоратором @staticmethod, должен проводить валидацию числа, месяца и года (например, месяц — от 1 до 12).
# Проверить работу полученной структуры на реальных данных.

class Date:
def __init__(self, d_m_y):
self.d_m_y = str(d_m_y)

@classmethod
def extraction(cls, d_m_y):
my_date = []

for i in d_m_y.split():
if i != '/':
my_date.append(i)

return int(my_date[0]), int(my_date[1]), int(my_date[2])

@staticmethod
def validation(d, m, y):
# if 1 <= d <= 31:
# return f'Date is correct!'
# else:
# f'Incorrect day'
#
# if 1 <= m <= 12:
# return f'Date is correct!'
# else:
# f'Incorrect month'
#
# if 0 <= y <= 2022:
# return f'Date is correct!'
# else:
# f'Incorrect year'

if 1 <= d <= 31:
if 1 <= m <= 12:
if 988 <= y <= 2050:
return f'The entered date is correct.'
else:
return f'Please enter correct year.'
else:
return f'Please enter correct month.'
else:
return f'Please enter correct day.'

def __str__(self):
return f'The current date is: {Date.extraction(self.d_m_y)}'


day = Date('3 / 4 / 2000')
print(day)

print(Date.validation(16, 6, 2022))
print(Date.validation(3, 15, 2000))
print(day.validation(3, 4, 950))
print(Date.extraction('3 / 4 / 2022'))
print(day.extraction('3 / 4 / 2022'))
22 changes: 22 additions & 0 deletions Lesson_8/task_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Создайте собственный класс-исключение, обрабатывающий ситуацию деления на ноль.
# Проверьте его работу на данных, вводимых пользователем.
# При вводе нуля в качестве делителя программа должна корректно обработать эту ситуацию
# и не завершиться с ошибкой.

class Division:
def __init__(self, divident, divider):
self.divident = divident
self.divider = divider

@staticmethod
def division_by_null(divident, divider):
try:
return (divident / divider)
except:
return (f'Division by null is not allowed!')


div = Division(25, 5)
print(Division.division_by_null(25, 0))
print(Division.division_by_null(45, 5))
print(div.division_by_null(25, 0))
29 changes: 29 additions & 0 deletions Lesson_8/task_3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Создайте собственный класс-исключение, который должен проверять содержимое списка на наличие только чисел.
# Проверить работу исключения на реальном примере. Запрашивать у пользователя данные и заполнять список
# необходимо только числами. Класс-исключение должен контролировать типы данных элементов списка.

class MyOwnErr:
def __init__(self, value):
self.value = value
self.my_list = []

def content(self, value):
while True:
try:
value = int(input(f'Please enter a number: '))
self.my_list.append(value)
print(f'The current list is: {self.my_list} \n')
except:
if type(value) != int():
print(f'This value is not allowed!')
else:
choice = input(f'Would you like to try again? (Y/N)? - ')

if choice == 'Y' or choice == 'y':
print(my_exception.content(value))
elif choice == 'N' or choice == 'n':
print(f'Exit done.')


my_exception = MyOwnErr(1)
print(my_exception.content(0))
25 changes: 25 additions & 0 deletions Lesson_8/task_7.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Реализовать проект «Операции с комплексными числами».
# Создайте класс «Комплексное число». Реализуйте перегрузку методов сложения и умножения комплексных чисел.
# Проверьте работу проекта. Для этого создаёте экземпляры класса (комплексные числа),
# выполните сложение и умножение созданных экземпляров. Проверьте корректность полученного результата.

class ComplexValue:
def __init__(self, a, b):
self.a = a
self.b = b
self.val = 'a + j * b'

def __add__(self, other):
print('The result of the addition is: ')
return f'val = {self.a + other.a} + {self.b + other.b}*j'

def __mul__(self, other):
print('The result of the multiplication is: ')
return f'val = ({self.a * other.a - self.b * other.b}) + ' \
f'({self.a * other.b + self.b * other.a})*j'


val_1 = ComplexValue(2, 5)
val_2 = ComplexValue(1, -3)
print(val_1 + val_2)
print(val_1 * val_2)