TelenkovDmitry 8 months ago
parent
commit
cd47e411ef
3 changed files with 317 additions and 15 deletions
  1. 159 13
      courses/python_oop/method_task.py
  2. 140 0
      courses/python_oop/method_task_2.py
  3. 18 2
      courses/python_oop/test.py

+ 159 - 13
courses/python_oop/method_task.py

@@ -74,24 +74,170 @@ class Registration:
         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 check_password_dictionary(value: str):
-    with open('easy_passwords.txt', 'r', encoding='utf-8') as f:
-        password_list = f.read().split('\n')
-        print(password_list)
-        # password_list = open('easy_passwords.txt', 'r', encoding='utf-8').read().split('\n')
-    return value in password_list
 
 def main():
-    # reg = Registration('asdfa@sfsdf.werwe', 'QwerTy123')
-    # reg = Registration('asdfa@sfsdf.werwe', 'QwerTy123')
-    # print(reg.login)
-    # print(reg.password)
 
-    # print(check_password_dictionary('124244242'))
-    # print(check_password_dictionary('as1SNdf'))
+    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:
@@ -195,7 +341,7 @@ def main():
         raise TypeError("Пароль должен быть строкой")
 
     print('U r hacked Pentagon')
-
+    '''
 
 
 if __name__ == '__main__':

+ 140 - 0
courses/python_oop/method_task_2.py

@@ -0,0 +1,140 @@
+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, count=1):
+        if number >= self.goods[product]:
+            number = self.goods[product]
+            self.goods[product] = self.goods.get(product, 0) - number
+            self.__total -= number * product.price
+        '''
+        else:
+            self.__total -= self.goods[product] * product.price
+            self.goods[product] = 0
+        '''
+
+    @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()

+ 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__':