TelenkovDmitry 8 月之前
父節點
當前提交
cb5cdb6c2d

+ 179 - 0
courses/python_oop/dunder_method/dunder_task.py

@@ -0,0 +1,179 @@
+
+class Vector:
+
+    def __init__(self, x, y):
+        self.x = x
+        self.y = y
+
+    def __add__(self, other):
+        if isinstance(other, Number):
+            return Vector(self.x + other.value, self.y + other.value)
+
+    def __str__(self):
+        return f"Vector({self.x},{self.y})"
+
+class Number:
+
+    def __init__(self, value) -> None:
+        self.value = value
+
+    def __radd__(self, other):
+        if isinstance(other, Vector):
+            return Number(other.x + other.y + self.value)
+        
+    def __str__(self) -> str:
+        return f"Number({self.value})"
+    
+
+class Rectangle:
+
+    def __init__(self, width, height) -> None:
+        self.width = width
+        self.height = height
+
+    def __add__(self, other):
+        return Rectangle(self.width + other.width, self.height + other.height)
+    
+    def __str__(self):
+        return f"Rectangle({self.width}x{self.height})"
+
+
+class Vector:
+    def __init__(self, x, y):
+        self.x = x
+        self.y = y
+
+    def __repr__(self):
+        return f"Vector({self.x}, {self.y})"
+
+    def __mul__(self, other):
+        return self.x * other.x + self.y * other.y
+    
+
+class Order:
+
+    def __init__(self, cart: list, customer):
+        self.cart = cart
+        self.customer = customer
+
+    def __add__(self, other):
+        new_cart = self.cart.copy()
+        new_cart.append(other)
+        return Order(new_cart, self.customer)
+    
+    def __radd__(self, other):
+        new_cart = self.cart.copy()
+        new_cart.insert(0, other)
+        return Order(new_cart, self.customer)
+
+    def __sub__(self, other):
+        new_cart = self.cart.copy()
+        if other in self.cart:
+            new_cart.remove(other)
+        return Order(new_cart, self.customer)
+
+    def __rsub__(self, other):
+        return self.__sub__(other)
+
+
+class Vector:
+
+    def __init__(self, *args):
+        foo = []
+        for i in args:
+            if isinstance(i, int):
+                foo.append(i)
+        self.values = sorted(foo)
+
+    def __str__(self):
+        if self.values:
+            foo = [str(i) for i in self.values]
+            return f"Вектор({', '.join(foo)})"
+        else:
+            return "Пустой вектор"
+
+    def __add__(self, other):
+        if isinstance(other, int):
+            foo = [i+other for i in self.values]
+            return Vector(*foo)
+        elif isinstance(other, Vector):
+            if len(other.values) == len(self.values):
+                foo = [sum(i) for i in zip(self.values, other.values)]
+                return Vector(*foo)
+            else:
+                print("Сложение векторов разной длины недопустимо")
+        else:
+            print(f"Вектор нельзя сложить с {other}")
+
+    def __mul__(self, other):
+        if isinstance(other, int):
+            foo = [i * other for i in self.values]
+            return Vector(*foo)
+        elif isinstance(other, Vector):
+            if len(other.values) == len(self.values):
+                foo = [i[0]*i[1] for i in zip(self.values, other.values)]
+                return Vector(*foo)
+            else:
+                print("Умножение векторов разной длины недопустимо")
+        else:
+            print(f"Вектор нельзя умножать с {other}")
+
+
+def main():
+    
+
+    '''
+    order = Order(['banana', 'apple'], 'Гена Букин')
+
+    order_2 = order + 'orange'
+
+    assert order.cart == ['banana', 'apple']
+    assert order.customer == 'Гена Букин'
+    assert order_2.cart == ['banana', 'apple', 'orange']
+
+    order = 'mango' + order
+    assert order.cart == ['mango', 'banana', 'apple']
+    order = 'ice cream' + order
+    assert order.cart == ['ice cream', 'mango', 'banana', 'apple']
+
+    order = order - 'banana'
+    assert order.cart == ['ice cream', 'mango', 'apple']
+
+    order3 = order - 'banana'
+    assert order3.cart == ['ice cream', 'mango', 'apple']
+
+    order = order - 'mango'
+    assert order.cart == ['ice cream', 'apple']
+
+    order = 'lime' - order
+    assert order.cart == ['ice cream', 'apple']
+    print('Good')
+    '''
+
+    '''
+    r1 = Rectangle(5, 10)
+    assert r1.width == 5
+    assert r1.height == 10
+    print(r1)
+
+    r2 = Rectangle(20, 5)
+    assert r2.width == 20
+    assert r2.height == 5
+    print(r2)
+
+    r3 = r2 + r1
+    assert isinstance(r3, Rectangle)
+    assert r3.width == 25
+    assert r3.height == 15
+    print(r3)
+    '''
+
+    '''
+    v = Vector(2, 3)
+    num = Number(5)
+    print(num + v)
+    '''
+    
+
+if __name__ == '__main__':
+    main()

+ 101 - 0
courses/python_oop/dunder_method/dunder_task_2.py

@@ -0,0 +1,101 @@
+# Магические методы сравнения
+# __eq__ - ==
+# __ne__ - !=
+# __lt__ <
+# __le__ <=
+# __gt__ >
+# __ge__ >=
+
+from functools import total_ordering
+
+class Rectangle:
+
+    def __init__(self, a, b) -> None:
+        self.a = a
+        self.b = b
+
+    @property
+    def area(self):
+        return self.a * self.b
+
+    def __eq__(self, other):
+        if isinstance(other, Rectangle):
+            return self.a == other.a and self.b == other.b
+        
+    def __eq__(self, other):
+        if isinstance(other, Rectangle):
+            return self.area < other.area
+        elif isinstance(other, (int, float)):
+            return self.area < other
+        
+    def __le__(self, other):
+        return self==other or  self<other
+
+
+class Point:
+    
+    def __init__(self, x, y) -> None:
+        self.x = x
+        self.y = y
+
+    def __eq__(self, other: object) -> bool:
+        return isinstance(other, Point) and \
+            self.x == other.x and self.y == other.y
+        
+    def __hash__(self):
+        return hash((self.x, self.y))
+
+
+@total_ordering
+class Fruit:
+
+    def __init__(self, name, price):
+        self.name = name
+        self.price = price
+
+    def __eq__(self, value: object) -> bool:
+        if isinstance(value, (int, float)):
+            return self.price == value
+        elif isinstance(value, Fruit):
+            return self.price == value.price
+        else:
+            raise ValueError
+
+    def __lt__(self, value):
+        if isinstance(value, (int, float)):
+            return self.price < value
+        elif isinstance(value, Fruit):
+            return self.price < value.price
+        else:
+            raise ValueError
+
+def main():
+    apple = Fruit("Apple", 0.5)
+    orange = Fruit("Orange", 1)
+    banana = Fruit("Banana", 1.6)
+    lime = Fruit("Lime", 1.0)
+
+    assert (banana > 1.2) is True
+    assert (banana >= 1.2) is True
+    assert (banana == 1.2) is False
+    assert (banana != 1.2) is True
+    assert (banana < 1.2) is False
+    assert (banana <= 1.2) is False
+
+    assert (apple > orange) is False
+    assert (apple >= orange) is False
+    assert (apple == orange) is False
+    assert (apple != orange) is True
+    assert (apple < orange) is True
+    assert (apple <= orange) is True
+
+    assert (orange == lime) is True
+    assert (orange != lime) is False
+    assert (orange > lime) is False
+    assert (orange < lime) is False
+    assert (orange <= lime) is True
+    assert (orange >= lime) is True
+    print('Good')
+
+if __name__ == '__main__':
+    main()

+ 160 - 0
courses/python_oop/dunder_method/misc.py

@@ -0,0 +1,160 @@
+'''
+Таким образом, разница между __str__ и __repr__ заключается в целях
+использования. __str__ предназначен для представления объекта в читаемой
+форме, а __repr__ предназначен для представления объекта в точном и воспроизводимом виде.
+'''
+
+class Lion:
+    def __init__(self, name):
+        self.name = name
+
+    '''Как видят объект разработчики'''
+    def __repr__(self) -> str:
+        return f'The name Lion - f{self.name}'
+
+    '''Как видят объект пользователи. Функции print, str'''
+    def __str__(self) -> str:
+        return f'Lion - f{self.name}'
+
+class Person:
+
+    def __init__(self, name, surname, gender='male'):
+        self.name = name
+        self.surname = surname
+        if gender not in ['male', 'female']:
+            print("Не знаю, что вы имели в виду? Пусть это будет мальчик!")
+            self.gender = 'male'
+        else:
+            self.gender = gender
+
+    def __str__(self):
+        if self.gender == 'male':
+            return f"Гражданин {self.surname} {self.name}"
+        else:
+            return
+
+    # Метод должен возвращать неотрицательное значение
+    def __len__(self):
+         return len(self.name + self.surname)
+
+
+class MyList:
+
+    def __init__(self, elements):
+        self.elements = elements
+
+    def __len__(self):
+        return len([elem for elem in self.elements if elem % 2 == 0])
+
+
+class Hero:
+
+    def __init__(self) -> None:
+        pass
+
+    def __len__(self):
+        return(len(self.__dict__))
+    
+    def __str__(self):
+        sorted_params = sorted(self.__dict__.items(), key=lambda item: item[0])
+        params = ''
+        for item in sorted_params:
+            params += f'{item[0]}: {item[1]}\n'
+        params = params[:len(params)-1]
+        return params
+
+class MyAtr:
+    
+    def __init__(self, name, surname) -> None:
+        self.name = name
+        self.surname = surname
+
+    def __str__(self) -> str:
+        for key, value in self.__dict__.items():
+            print(key, value)
+
+        return "hello"
+
+        
+'''Математические методы'''
+class BankAccount:
+    def __init__(self, name, balance):
+        print('new_object init')
+        self.name = name
+        self.balance = balance
+
+    def __repr__(self):
+        return f"Клиент {self.name} с балансом {self.balance}"
+
+    def __add__(self, other):
+        print('__add__ call')
+        if isinstance(other, BankAccount):
+            return self.balance + other.balance
+        if isinstance(other, (int, float)):
+            return BankAccount(self.name, self.balance + other)
+        raise NotImplemented
+
+    def __radd__(self, other):
+        print('__radd__ call')
+        return self + other
+    
+    def __mul__(self, other):
+        print('__add__ call')
+        if isinstance(other, BankAccount):
+            return self.balance * other.balance
+        if isinstance(other, (int, float)):
+            return self.balance * other
+        if isinstance(other, str):
+            return self.name + other
+        raise NotImplemented
+
+    
+
+def main():
+
+    hero = Hero()
+    assert len(hero) == 0
+    hero.health = 50
+    hero.damage = 10
+    assert len(hero) == 2
+    assert str(hero) == '''damage: 10
+    health: 50'''
+    hero.weapon = ['sword', ' bow']
+    hero.skill = 'Некромант'
+    assert str(hero) == '''damage: 10
+    health: 50
+    skill: Некромант
+    weapon: ['sword', ' bow']'''
+    print(hero)
+
+    villain = Hero()
+    assert str(villain) == ''
+    assert len(villain) == 0
+    villain.level = 15
+    villain.skill = 'Боец'
+    villain.armor = 25
+    assert len(villain) == 3
+    assert str(villain) == '''armor: 25
+    level: 15
+    skill: Боец'''
+    print(villain)
+
+
+    # at = MyAtr('Ivan', 'Ivanov')
+    # print(at)
+
+    # hero = Hero()
+    # print(len(hero))
+
+    '''
+    lion = Lion('Simba')
+    print(lion) # __str__
+    print(lion) # __str__
+    '''
+
+    # my_list = MyList([1, 2, 3, 4, 5, 6, 7])
+    # print(len(my_list))
+    
+
+if __name__ == '__main__':
+    main()

+ 164 - 0
courses/python_oop/dunder_method/poly.py

@@ -0,0 +1,164 @@
+# Полиморфизм
+
+# Проблема 
+
+from functools import total_ordering
+
+class Rectangle:
+    def __init__(self, a, b):
+        self.a = a
+        self.b = b
+
+    def get_area(self):
+        return self.a * self.b
+    
+
+class Square:
+
+    def __init__(self, a) -> None:
+        self.a = a
+
+    def get_area(self):
+        return self.a**2
+
+
+class Circle:
+
+    def __init__(self, r):
+        self.r = r
+
+    def get_area(self):
+        return 3.14*self.r**2
+        
+
+class UnitedKingdom:
+
+    def __init__(self) -> None:
+        pass
+
+    @staticmethod
+    def get_capital():
+        print("London is the capital of Great Britain.")
+
+    @staticmethod
+    def get_language():
+        print("English is the primary language of Great Britain.")
+
+
+class Spain:
+
+    def __init__(self):
+        pass
+
+    @staticmethod
+    def get_capital():
+        print("Madrid is the capital of Spain.")
+
+    @staticmethod
+    def get_language():
+        print("Spanish is the primary language of Spain.")
+
+
+class DateUSA:
+
+    def __init__(self, day, month, year) -> None:
+        self.day = day
+        self.month = month
+        self.year = year
+
+    def format(self):
+        return f"{self.month:02}/{self.day:02}/{self.year:04}"
+    
+    def isoformat(self):
+        return f"{self.year:04}-{self.month:02}-{self.day:02}"
+
+class DateEurope:
+    
+    def __init__(self, day, month, year):
+        self.day = day
+        self.month = month
+        self.year = year
+
+    def format(self):
+        return f"{self.day:02}/{self.month:02}/{self.year:02}"
+    
+    def isoformat(self):
+        return f"{self.year:04}-{self.month:02}-{self.day:02}"
+
+
+@total_ordering
+class BankAccount:
+    def __init__(self, name, balance):
+        self.name = name
+        self.balance = balance
+
+    def __str__(self):
+        return self.name
+    
+    def __len__(self):
+        return len(str(self))
+
+    def __lt__(self, other):
+        if isinstance(other, BankAccount):
+            return self.balance < other.balance
+        elif isinstance(other, int):
+            return self.balance < other
+        else:
+            raise ValueError
+
+    def __add__(self, other):
+        if isinstance(other, BankAccount):
+            return self.balance + other.balance
+        elif isinstance(other, Numbers):
+            return self.balance + sum(other._values)
+        elif isinstance(other, (int, float)):
+            return self.balance + other
+        else:
+            raise ValueError
+
+    def __radd__(self, other):
+        return self.__add__(other)
+
+
+class Numbers:
+
+    def __init__(self, values: list):
+        self._values = values
+
+    def __add__(self, other):
+        if isinstance(other, Numbers):
+            return sum(other._values) + sum(other._values)
+        elif isinstance(other, BankAccount):
+            return sum(self._values) + other.balance
+        elif isinstance(other, (int, float)):
+            return sum(self._values) + other
+        else:
+            raise ValueError
+        
+    def __radd__(self, other):
+        return self.__add__(other)
+    
+
+def main():
+
+    lst = [4, BankAccount('Petr', 100), 5]
+    print(sum(lst))
+
+    # usa = DateUSA(1, 3, 2016)
+    # print(usa.format())
+
+    '''
+    rect1 = Rectangle(3, 4)
+    rect2 = Rectangle(12, 5)
+
+    sq1 = Square(4)
+    sq2 = Square(5)
+
+    figures = [rect1, rect2, sq1, sq2]
+    for figure in figures:
+        print(figure.get_area())
+    '''
+
+
+if __name__ == '__main__':
+    main()

+ 32 - 0
courses/python_oop/easy_passwords.txt

@@ -0,0 +1,32 @@
+123456
+password
+123456789
+12345
+12345678
+qwerty
+1234567
+111111
+1234567890
+123123
+abc123
+1234
+password1
+iloveyou
+1q2w3e4r
+000000
+qwerty123
+zaq12wsx
+dragon
+sunshine
+princess
+letmein
+654321
+QwerTy123
+KissasSAd1f
+monkey
+27653
+1qaz2wsx
+123321
+qwertyuiop
+superman
+asdfghjkl

+ 85 - 0
courses/python_oop/inheritance/inh_1.py

@@ -0,0 +1,85 @@
+# Наследование
+
+# issubclass(sub, par)
+# 15.__class__ # узнать тип объекта
+# 15.__base__ # хранит ссылку на родителя
+
+class Vehicle:
+    
+    def __init__(self, name, max_speed, mileage):
+        self.name = name
+        self.max_speed = max_speed
+        self.mileage = mileage
+
+    def display_info(self):
+        print(f"Vehicle Name: {self.name}, Speed: {self.max_speed}, Mileage: {self.mileage}")
+
+
+class Bus(Vehicle):
+    pass
+
+
+class Person:
+    
+    def __init__(self, name):
+        self.name = name
+
+    def get_name(self):
+        return self.name
+    
+    def is_employee(self):
+        return False
+    
+
+class Employee(Person):
+
+    def is_employee(self):
+        return True
+    
+
+class Shape:
+    pass
+
+class Ellipse(Shape):
+    pass
+
+class Circle(Ellipse):
+    pass
+
+class Polygon(Shape):
+    pass
+
+class Triangle(Polygon):
+    pass
+
+class Rectangle(Polygon):
+    pass
+
+class Square(Rectangle):
+    pass
+
+
+class MyList(list):
+    def remove_all(self, value):
+        self[:] = [i for i in self if value != i]
+
+
+class NewInt(int):
+
+    def repeat(self, value=2):
+        return int(str(self)*value)
+    
+    def to_bin(self):
+        return int(bin(self)[2:])
+
+
+def main():
+    i = NewInt(34)
+    print(i.repeat(3))
+    print(i.to_bin())
+    
+
+
+if __name__ == "__main__":
+    main()
+

+ 43 - 0
courses/python_oop/inheritance/inh_2.py

@@ -0,0 +1,43 @@
+
+class PrettyPrint:
+
+    def __str__(self):
+        if len(self.__dict__):
+            st = f"{self.__class__.__name__}("
+            for key, value in self.__dict__.items():
+                st += f'{key}={value}, '
+            return st[:len(st)-2] + ')'
+        else:
+            return f"{self.__class__.__name__}()"
+     
+
+class Empty(PrettyPrint):
+    pass
+
+class Person(PrettyPrint):
+
+    def __init__(self, first_name, last_name, age):
+        self.first_name = first_name
+        self.last_name = last_name
+        self.age = age
+
+    # def __str__(self):
+    #     return f"__str__ class Person"
+
+
+    
+
+def main():
+
+    empty = Empty()
+    print(empty)
+
+    # artem = Person('Artem', 'Egorov', 33)
+    # ivan = Person('Ivan', 'Ivanov', 45)
+    # print(artem)
+    # # print(ivan)
+
+if __name__ == '__main__':
+    main()
+
+

+ 16 - 0
courses/python_oop/inheritance/object.py

@@ -0,0 +1,16 @@
+
+
+
+def main():
+    print(isinstance(int, object))
+    # print(object.__dict__)
+
+    ob = object()
+    print(ob.__str__())
+
+    int_object = int(8).bit_length()
+    print(int_object)
+
+
+if __name__ == '__main__':
+    main()

+ 52 - 0
courses/python_oop/method_practic.py

@@ -0,0 +1,52 @@
+
+# Практика по property
+
+from string import digits
+
+class User:
+
+    def __init__(self, login, password) -> None:
+        self.login = login
+        self.password = password
+        self.__secret = 'abracadabra'
+        
+    @property
+    def secret(self):
+        s = input("Введите ваш пароль: ")
+        if s == self.password:
+            return self.__secret
+        else:
+            raise ValueError("Доступ закрыт")
+
+    @property
+    def password(self):
+        print('getter called')
+        return self.__password
+
+    @staticmethod
+    def is_include_number(password):
+        for digit in digits:
+            if digit in password:
+                return True
+        return False
+
+    @password.setter
+    def password(self, value):
+        print('setter called')
+        if not isinstance(value, str):
+            raise TypeError("Пароль должен быть строкой")
+        if len(value) < 4:
+            raise ValueError("Длина пароля должна быть не менее 4-ех символов")
+        if len(value) > 12:
+            raise ValueError("Длина пароля должна быть не более 12-и символов")
+        if not User.is_include_number(value):
+            raise ValueError("Пароль должен содержать хотя бы одну цифру")
+        self.__password = value
+
+
+def main():
+    user1 = User('Ivan', '123df')
+
+
+if __name__ == '__main__':
+    main()

+ 348 - 0
courses/python_oop/method_task.py

@@ -0,0 +1,348 @@
+from string import digits, ascii_letters
+
+
+class Registration:
+
+    def __init__(self, login, password) -> None:
+        self.login = login
+        self.password = password
+
+    @property
+    def login(self):
+        return self.__login
+    
+    @login.setter
+    def login(self, value: str):
+        if not isinstance(value, str):
+            raise TypeError
+        if '@' not in value:
+            raise ValueError
+        if value.rfind('.') < value.rfind('@'):
+            raise ValueError
+        self.__login = value
+
+    @staticmethod
+    def is_include_digit(value: str):
+        for i in value:
+            if i in digits:
+                return True
+        return False
+    
+    @staticmethod
+    def is_include_all_register(value: str):
+        upper = False
+        lower = False
+        for i in value:
+            if not lower:
+                lower = i.islower()
+            if not upper:
+                upper = i.isupper()
+        return lower and upper
+
+    @staticmethod
+    def is_include_only_latin(value: str):
+        for i in value:
+            if not i.isdigit():
+                if  i not in ascii_letters:
+                    return False
+        return True        
+
+    @staticmethod
+    def check_password_dictionary(value: str):
+        with open('easy_passwords.txt', 'r', encoding='utf-8') as f:
+            password_list = f.read().split('\n')
+        return value in password_list
+    
+    @property
+    def password(self):
+        return self.__password
+    
+    @password.setter
+    def password(self, value: str):
+        if not isinstance(value, str):
+            raise TypeError("Пароль должен быть строкой")
+        if len(value) < 5 or len(value) > 11:
+            raise ValueError("Пароль должен быть длиннее 4 и меньше 12 символов")
+        if not self.is_include_digit(value):
+            raise ValueError("Пароль должен содержать хотя бы одну цифру")
+        if not self.is_include_all_register(value):
+            raise ValueError("Пароль должен содержать хотя бы один символ верхнего и нижнего регистра")
+        if not self.is_include_only_latin(value):
+            raise ValueError("Пароль должен содержать только латинский алфавит")
+        if self.check_password_dictionary(value):
+            raise ValueError("Ваш пароль содержится в списке самых легких")
+        self.__password = value
+
+
+class File:
+
+    def __init__(self, name) -> None:
+        self.name = name
+        self.in_trash = False
+        self.is_deleted = False
+
+    def restore_from_trash(self):
+        print(f"Файл {self.name} восстановлен из корзины")
+        self.in_trash = False
+
+    def remove(self):
+        print(f"Файл {self.name} был удален")
+        self.is_deleted = True
+
+    def read(self):
+        if self.is_deleted == True:
+            print(f"ErrorReadFileDeleted({self.name})")
+            return
+        if self.in_trash == True:
+            print(f"ErrorReadFileTrashed({self.name})")
+            return
+        print(f"Прочитали все содержимое файла {self.name}")
+
+    def write(self, content):
+        if self.is_deleted:
+            print(f"ErrorWriteFileDeleted({self.name})")
+            return
+        if self.in_trash:
+            print(f"ErrorWriteFileTrashed({self.name})")
+            return
+        print(f"Записали значение {content} в файл {self.name}")
+
+
+class Trash:
+
+    content = []
+
+    def __init__(self):
+        pass
+
+    @staticmethod
+    def add(file: File):
+        if not isinstance(file, File):
+            print("В корзину можно добавлять только файл")
+        else:
+            file.in_trash = True
+            Trash.content.append(file)
+
+    @staticmethod
+    def clear():
+        print("Очищаем корзину")
+        while Trash.content:
+            Trash.content[0].remove()
+            Trash.content.pop(0)
+        print("Корзина пуста")
+
+    @staticmethod
+    def restore():
+        print("Восстанавливаем файлы из корзины")
+        while Trash.content:
+            Trash.content[0].restore_from_trash()
+            Trash.content.pop(0)
+        print("Корзина пуста")
+
+
+
+
+
+
+def main():
+
+    f1 = File('puppies.jpg')
+    f2 = File('cat.jpg')
+    f3 = File('xxx.doc')
+    passwords = File('pass.txt')
+
+    for file in [f1, f2, f3, passwords]:
+        assert file.is_deleted is False
+        assert file.in_trash is False
+
+    f3.read()
+    f3.remove()
+    assert f3.is_deleted is True
+    f3.read()
+    f3.write('hello')
+
+    assert Trash.content == []
+
+    Trash.add(f2)
+    Trash.add(passwords)
+    Trash.add(f3)
+
+    f1.read()
+    Trash.add(f1)
+    f1.read()
+
+    for file in [f1, f2, f3, passwords]:
+        assert file.in_trash is True
+
+    for f in [f2, passwords, f3, f1]:
+        assert f in Trash.content
+
+    Trash.restore()
+    assert Trash.content == [], 'После восстановления корзина должна была очиститься'
+
+    Trash.add(passwords)
+    Trash.add(f2)
+    Trash.add('hello')
+    Trash.add(f1)
+
+    for f in [passwords, f2, f1]:
+        assert f in Trash.content
+
+
+    Trash.clear()
+
+    for file in [passwords, f2, f1]:
+        assert file.is_deleted is True
+
+    assert Trash.content == [], 'После удаления файлов корзина должна была очиститься'
+
+    f1.read()
+
+    '''
+    f1 = File('puppies.jpg')
+    assert f1.name == 'puppies.jpg'
+    assert f1.in_trash is False
+    assert f1.is_deleted is False
+
+    f1.read()  # Прочитали все содержимое файла puppies.jpg
+    f1.remove()  # Файл puppies.jpg был удален
+    assert f1.is_deleted is True
+    f1.read()  # ErrorReadFileDeleted(puppies.jpg)
+
+    passwords = File('pass.txt')
+    assert passwords.name == 'pass.txt'
+    assert passwords.in_trash is False
+    assert passwords.is_deleted is False
+
+    f3 = File('xxx.doc')
+
+    assert f3.__dict__ == {'name': 'xxx.doc', 'in_trash': False, 'is_deleted': False}
+    f3.read()
+    f3.remove()
+    assert f3.is_deleted is True
+    f3.read()
+    f3.in_trash = True
+    f3.is_deleted = False
+    f3.read()
+    f3.write('hello')
+    f3.restore_from_trash()
+    assert f3.in_trash is False
+    f3.write('hello')  # Записали значение «hello» в файл cat.jpg
+
+    f2 = File('cat.jpg')
+    f2.write('hello')  # Записали значение «hello» в файл cat.jpg
+    f2.write([1, 2, 3])  # Записали значение «hello» в файл cat.jpg
+    f2.remove()  # Файл cat.jpg был удален
+    f2.write('world')  # ErrorWriteFileDeleted(cat.jpg)
+    '''
+    
+
+    '''
+    try:
+        s2 = Registration("fga", "asd12")
+    except ValueError as e:
+        pass
+    else:
+        raise ValueError("Registration('fga', 'asd12') как можно записать такой логин?")
+
+    try:
+        s2 = Registration("fg@a", "asd12")
+    except ValueError as e:
+        pass
+    else:
+        raise ValueError("Registration('fg@a', 'asd12') как можно записать такой логин?")
+
+    s2 = Registration("translate@gmail.com", "as1SNdf")
+    try:
+        s2.login = "asdsa12asd."
+    except ValueError as e:
+        pass
+    else:
+        raise ValueError("asdsa12asd как можно записать такой логин?")
+
+    try:
+        s2.login = "asdsa12@asd"
+    except ValueError as e:
+        pass
+    else:
+        raise ValueError("asdsa12@asd как можно записать такой логин?")
+
+    assert Registration.check_password_dictionary('QwerTy123'), 'проверка на пароль в слове не работает'
+
+    try:
+        s2.password = "QwerTy123"
+    except ValueError as e:
+        pass
+    else:
+        raise ValueError("QwerTy123 хранится в словаре паролей, как его можно было сохранить?")
+
+
+    try:
+        s2.password = "KissasSAd1f"
+    except ValueError as e:
+        pass
+    else:
+        raise ValueError("KissasSAd1f хранится в словаре паролей, как его можно было сохранить?")
+
+    try:
+        s2.password = "124244242"
+    except ValueError as e:
+        pass
+    else:
+        raise ValueError("124244242 пароль НЕОЧЕНЬ, как его можно было сохранить?")
+
+    try:
+        s2.password = "RYIWUhjkdbfjfgdsffds"
+    except ValueError as e:
+        pass
+    else:
+        raise ValueError("RYIWUhjkdbfjfgdsffds пароль НЕОЧЕНЬ, как его можно было сохранить?")
+
+    try:
+        s2.password = "CaT"
+    except ValueError as e:
+        pass
+    else:
+        raise ValueError("CaT пароль НЕОЧЕНЬ, как его можно было сохранить?")
+
+    try:
+        s2.password = "monkey"
+    except ValueError as e:
+        pass
+    else:
+        raise ValueError("monkey пароль НЕОЧЕНЬ, как его можно было сохранить?")
+
+    try:
+        s2.password = "QwerTy123"
+    except ValueError as e:
+        pass
+    else:
+        raise ValueError("QwerTy123 пароль есть в слове, нельзя его использовать")
+
+    try:
+        s2.password = "HelloQEWq"
+    except ValueError as e:
+        pass
+    else:
+        raise ValueError("HelloQEWq пароль НЕОЧЕНЬ, как его можно было сохранить?")
+
+    try:
+        s2.password = [4, 32]
+    except TypeError as e:
+        pass
+    else:
+        raise TypeError("Пароль должен быть строкой")
+
+    try:
+        s2.password = 123456
+    except TypeError as e:
+        pass
+    else:
+        raise TypeError("Пароль должен быть строкой")
+
+    print('U r hacked Pentagon')
+    '''
+
+
+if __name__ == '__main__':
+    main()

+ 136 - 0
courses/python_oop/method_task_2.py

@@ -0,0 +1,136 @@
+from collections import defaultdict
+
+
+class Product:
+    
+    def __init__(self, name, price):
+        self.name = name
+        self.price = price
+
+
+class User:
+
+    def __init__(self, login, balance=0):
+        self.login = login
+        self.balance = balance
+
+    @property
+    def balance(self):
+        return self.__balance
+    
+    @balance.setter
+    def balance(self, value):
+        self.__balance = value
+
+    def __str__(self):
+        return f"Пользователь {self.login}, баланс - {self.balance}"
+
+    def deposit(self, value):
+        self.balance += value
+
+    def is_money_enough(self, value):
+        return value <= self    .balance
+    
+    def payment(self, value):
+        if self.is_money_enough(value):
+            self.balance -= value
+            return True
+        else:
+            print("Не хватает средств на балансе. Пополните счет")
+            return False
+
+
+class Cart:
+
+    def __init__(self, user:User) -> None:
+        self.user = user
+        self.goods = defaultdict()
+        self.__total = 0
+
+    def add(self, product:Product, count=1):
+        if product not in self.goods.keys():
+            self.goods[product] = count
+        else:
+            self.goods[product] += count
+
+        self.__total += product.price * count
+    
+    def remove(self, product:Product, number=1):
+        if number >= self.goods[product]:
+            number = self.goods[product]
+            self.goods[product] = self.goods.get(product, 0) - number
+            self.__total -= number * product.price
+
+
+    @property
+    def total(self):
+        return self.__total
+    
+    def order(self):
+        order_price = 0
+        for key in self.goods.keys():
+            order_price += key.price * self.goods[key]
+        if self.user.payment(order_price):
+            print("Заказ оплачен")
+        else:
+            print("Проблема с оплатой")
+
+    def print_check(self):
+        sorted_list = sorted(self.goods, key=lambda x: x.name)
+        print("---Your check---")
+        for element in sorted_list:
+            if self.goods[element] > 0:
+                print(f"{element.name} {element.price} {self.goods[element]} {element.price*self.goods[element]}")
+        print(f"---Total: {self.total}---")
+
+
+
+def main():
+
+    billy = User('billy@rambler.ru')
+
+    lemon = Product('lemon', 20)
+    carrot = Product('carrot', 30)
+
+    cart_billy = Cart(billy)
+    print(cart_billy.user) # Пользователь billy@rambler.ru, баланс - 0
+    cart_billy.add(lemon, 2)
+    cart_billy.add(carrot)
+    cart_billy.print_check()
+    ''' Печатает текст ниже
+    ---Your check---
+    carrot 30 1 30
+    lemon 20 2 40
+    ---Total: 70---'''
+    cart_billy.add(lemon, 3)
+    cart_billy.print_check()
+    ''' Печатает текст ниже
+    ---Your check---
+    carrot 30 1 30
+    lemon 20 5 100
+    ---Total: 130---'''
+    cart_billy.remove(lemon, 6)
+    cart_billy.print_check()
+    ''' Печатает текст ниже
+    ---Your check---
+    carrot 30 1 30
+    ---Total: 30---'''
+    print(cart_billy.total) # 30
+    cart_billy.add(lemon, 5)
+    cart_billy.print_check()
+    ''' Печатает текст ниже
+    ---Your check---
+    carrot 30 1 30
+    lemon 20 5 100
+    ---Total: 130---'''
+    cart_billy.order()
+    ''' Печатает текст ниже
+    Не хватает средств на балансе. Пополните счет
+    Проблема с оплатой'''
+    cart_billy.user.deposit(150)
+    cart_billy.order() # Заказ оплачен
+    print(cart_billy.user.balance) # 20
+
+
+if __name__ == '__main__':
+    main()

+ 198 - 0
courses/python_oop/namespace.py

@@ -0,0 +1,198 @@
+
+class DepartmentIT:
+    PYTHON_DEV = 3
+    GO_DEV = 3
+    REACT_DEV = 2
+
+    def info(self):
+        print(self.PYTHON_DEV, self.GO_DEV, self.REACT_DEV)
+
+    @property
+    def info_prop(self):
+        print(self.PYTHON_DEV, self.GO_DEV, self.REACT_DEV)
+
+
+class MyClass:
+    class_attribute = 'I am a class attribute'
+
+    def __init__(self) -> None:
+        self.instance_attribute = 'I am an instatnce attribute'
+
+    @classmethod
+    def create_attr(cls, attr_name, attr_value):
+        setattr(cls, attr_name, attr_value)
+
+
+class Container:
+    items = []
+
+    def add_item(self, value):
+        # self.items.append(value)
+        self.items = [value] + self.items
+
+
+class Robot:
+
+    population = 0
+    my_list = []
+
+    def __init__(self, name) -> None:
+        # Robot.population += 1
+        self.population += 1
+        self.name = name
+        self.my_list.append(name)
+        print(f'Робот {self.name} был создан')
+
+    def destroy(self):
+        print(f'Робот {self.name} был уничтожен')
+        # Robot.population -= 1
+        self.population -= 1
+
+    def say_hello(self):
+        print(f'Робот {self.name} приветствует тебя, особь человеческого рода')
+
+    def how_many_new(self):
+        print(f'{self.population}, вот сколько нас еще осталось')
+
+    @classmethod
+    def how_many(cls):
+        # print(f'{cls.population}, вот сколько нас еще осталось')
+        print(f'{cls.population}, вот сколько нас еще осталось')
+        
+
+class User:
+
+    def __init__(self, name, role) -> None:
+        self.name = name
+        self.role = role
+
+
+class Access:
+
+    __access_list = ['admin', 'developer']
+
+    def __init__(self) -> None:
+        pass
+
+    @staticmethod
+    def __check_access(role):
+        return True if role in Access.__access_list else False
+
+    @staticmethod
+    def get_access(user: User):
+        if not isinstance(user, User):
+            print('AccessTypeError')
+            return
+        if Access.__check_access(user.role):
+            print(f'User {user.name}: success')
+        else:
+            print(f'AccessDenied')
+
+
+class BankAccount:
+
+    bank_name = 'Tinkoff Bank'
+    address = 'Москва, ул. 2-я Хуторская, д. 38А'
+
+    def __init__(self, name, balance) -> None:
+        self.name = name
+        self.balance = balance
+
+    @classmethod
+    def create_account(cls, name, balance):
+        return cls(name, balance)
+    
+    @classmethod
+    def bank_info(cls):
+        return f"{cls.bank_name} is located in {cls.address}"
+
+
+def main():
+
+    oleg = BankAccount.create_account("Олег Тинкофф", 1000)
+    assert isinstance(oleg, BankAccount)
+    assert oleg.name == 'Олег Тинкофф'
+    assert oleg.balance == 1000
+    assert BankAccount.bank_info() == 'Tinkoff Bank is located in Москва, ул. 2-я Хуторская, д. 38А'
+
+    ivan = BankAccount.create_account("Ivan Reon", 50)
+    assert isinstance(ivan, BankAccount)
+    assert ivan.name == 'Ivan Reon'
+    assert ivan.balance == 50
+    print('Good')
+
+    '''
+    user1 = User('batya99', 'admin')
+    Access.get_access(user1) # печатает "User batya99: success"
+
+    zaya = User('milaya_zaya999', 'user')
+    Access.get_access(zaya) # печатает AccessDenied
+
+    Access.get_access(5) # печатает AccessTypeError
+    '''
+
+    '''
+    box1 = Container()
+    box1.add_item(2)
+    box1.add_item(4)
+
+
+    box2 = Container()
+    box2.add_item(5)
+    box2.add_item(7)
+
+    print(Container.items)
+    '''
+
+    '''
+    droid1 = Robot("R2-D2")
+    print(droid1.name)
+    print(Robot.population)
+    assert droid1.name == 'R2-D2'
+    # assert Robot.population == 1
+    droid1.say_hello()
+    Robot.how_many()
+    droid1.how_many_new()
+    droid2 = Robot("C-3PO")
+    assert droid2.name == 'C-3PO'
+    # assert Robot.population == 2
+    droid2.say_hello()
+    droid2.how_many_new()
+    Robot.how_many()
+    droid1.how_many_new()
+    droid1.destroy()
+    # assert Robot.population == 1
+    droid2.destroy()
+    # assert Robot.population == 0
+    Robot.how_many()
+    '''
+    
+
+    '''
+    example_1 = MyClass()
+    example_2 = MyClass()
+    example_3 = MyClass()
+
+    example_1.create_attr('new_attr', 'Hello world')
+
+    print(example_1.new_attr)
+    print(example_2.new_attr)
+    print(example_3.new_attr)
+    '''
+    
+    '''
+    dep1 = DepartmentIT()
+    dep2 = DepartmentIT()
+
+    print(dep1.REACT_DEV)
+    dep1.REACT_DEV = 5
+    print(dep1.REACT_DEV)
+    print(dep2.REACT_DEV)
+
+    dep3 = DepartmentIT()
+    print(dep3.REACT_DEV)
+    '''
+
+
+if __name__ == '__main__':
+    main()

+ 18 - 2
courses/python_oop/test.py

@@ -3,14 +3,30 @@ def format(value: int):
     value = 123.123456
     print("value =", "%.2f" % value)
 
-def list_test():
+def list_test_1():
     my_list = ['asd', 'qwer', 'qrtyer']
     for i, j in enumerate(my_list):
         print(i, j)
 
+def list_test_2():
+    my_list = [1, 2, 3, 4, 5]
+    while my_list:
+        my_list.pop(0)
+        print(my_list)
+
+# Сортировка словаря
+def test_dict_1():
+    my_dict = {'Иван': 3, 'Борис': 5}
+    list_keys = list(my_dict)
+    list_keys.sort()
+    print(list_keys)
+    # my_dict = sorted(my_dict, key=lambda x: x.k)
+    
+
 def main():
     # format(1)
-    list_test()
+    # list_test_2()
+    test_dict_1()
 
 
 if __name__ == '__main__':