Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Лаб. 4 Python

.docx
Скачиваний:
1
Добавлен:
31.08.2024
Размер:
116.87 Кб
Скачать

class Product: def __init__(self, name, price): self.name = name self.price = price def __add__(self, other): if isinstance(other, int): return self.price + other elif isinstance(other, float): return self.price + other else: print("Ошибка сложения (сложение не произведено)!\n") return self.price def display_info(self): print(f"Товар: {self.name}\nЦена: {self.price}\n")

from Product import Product class DiscountedProduct(Product): def __init__(self, name, price, discount): super().__init__(name, price) self.discount = discount def reducing_price(self): self.price = self.price - (self.discount * self.price / 100) return round(self.price, 2) def display_info(self): print(f"Товар: {self.name}\nЦена со скидкой: {self.price}\nСкидка: {self.discount}\n")

from Product import Product class ProductBox(Product): def __init__(self, name, price, width, height, depth): super().__init__(name, price) self.width = width self.height = height self.depth = depth def get_quantity(self, boxWidth, boxHeight, boxDepth): quantity = (boxWidth // self.width) * (boxHeight // self.height) * (boxDepth // self.depth) return int(quantity)

import re import pickle class NotCyrillic(Exception): pass def nameProductCheck(nameProduct): symbols = "^[а-яА-ЯёЁ]+$" try: check = re.match(symbols, nameProduct) is not None if check == True: return nameProduct else: raise NotCyrillic("Ошибка ввода!") except NotCyrillic as e: print(e) return False def priceProductCheck(priceProduct): try: priceProduct = float(priceProduct) if priceProduct < 0.1: print("Невозможная цена!") return False else: return priceProduct except ValueError: print("Ошибка ввода!") return False def discountProductCheck(discountProduct): try: discountProduct = float(discountProduct) if discountProduct < 1 or discountProduct > 99: print("Невозможная скидка!") return False else: return discountProduct except ValueError: print("Ошибка ввода!") return False def sizeProductCheck(sizeProduct): try: sizeProduct = float(sizeProduct) if sizeProduct < 1: print("Невозможный размер!") return False else: return sizeProduct except ValueError: print("Ошибка ввода!") return False def loadAndReadListInFile(fileName, allInformation, textInformation): try: if type(allInformation) != list: print("allInformation - не является списком!") return False if type(textInformation) != list: print("textInformation - не является списком!") return False if len(allInformation) != len(textInformation): print("Списки разных размеров!") return False with open(fileName, "wb") as file: for i in range(len(allInformation)): pickle.dump(allInformation[i], file) except IOError as e: print("\033[31mОшибка при записи файла:") print(f"\033[31mIOError: {e}") return False except TypeError as e: print("\033[31mОшибка при записи файла:") print(f"\033[31mTypeError: {e}") return False except IndexError as e: print("\033[31mОшибка при записи файла:") print(f"\033[31mIndexError: {e}") return False except Exception as e: print("\033[31mОшибка при записи файла:") print(f"\033[31mError: {e}") return False else: try: with open(fileName, "rb") as fileBin: for i in range(len(allInformation)): print(f"{textInformation[i]}: {pickle.load(fileBin)}") except FileNotFoundError: print("\033[31mОшибка при чтении файла:") print(f"Файла под именем {fileName} не существует!") return False except TypeError as e: print("\033[31mОшибка при чтении файла:") print(f"\033[31mTypeError: {e}") return False except IndexError as e: print("\033[31mОшибка при чтении файла:") print(f"\033[31mIndexError: {e}") return False except Exception as e: print("\033[31mОшибка при чтении файла:") print(f"\033[31mError: {e}") return False else: return True

import function as f from Product import Product from DiscountedProduct import DiscountedProduct from ProductBox import ProductBox allInformation = [] nameProduct = f.nameProductCheck(input("Введите название товара: ")) while nameProduct == False: nameProduct = f.nameProductCheck(input("Введите название товара: ")) allInformation.append(nameProduct) priceProduct = f.priceProductCheck(input("Введите цену товара: ")) while priceProduct == False: priceProduct = f.priceProductCheck(input("Введите цену товара: ")) allInformation.append(priceProduct) discountProduct = f.discountProductCheck(input("Введите размер скидки на товар (в процентах от 1 до 99 включительно): ")) while discountProduct == False: discountProduct = f.discountProductCheck(input("Введите размер скидки на товар (в процентах от 1 до 99 включительно): ")) allInformation.append(discountProduct) widthProduct = f.sizeProductCheck(input("Введите ширину товара (в миллиметрах): ")) while widthProduct == False: widthProduct = f.sizeProductCheck(input("Введите ширину товара (в миллиметрах): ")) allInformation.append(widthProduct) heightProduct = f.sizeProductCheck(input("Введите высоту товара (в миллиметрах): ")) while heightProduct == False: heightProduct = f.sizeProductCheck(input("Введите высоту товара (в миллиметрах): ")) allInformation.append(heightProduct) depthProduct = f.sizeProductCheck(input("Введите глубину товара (в миллиметрах): ")) while depthProduct == False: depthProduct = f.sizeProductCheck(input("Введите глубину товара (в миллиметрах): ")) allInformation.append(depthProduct) widthBox = f.sizeProductCheck(input("Введите ширину коробки (в миллиметрах): ")) while widthBox == False: widthBox = f.sizeProductCheck(input("Введите ширину коробки (в миллиметрах): ")) allInformation.append(widthBox) heightBox = f.sizeProductCheck(input("Введите высоту коробки (в миллиметрах): ")) while heightBox == False: heightBox = f.sizeProductCheck(input("Введите высоту коробки (в миллиметрах): ")) allInformation.append(heightBox) depthBox = f.sizeProductCheck(input("Введите глубину коробки (в миллиметрах): ")) while depthBox == False: depthBox = f.sizeProductCheck(input("Введите глубину коробки (в миллиметрах): ")) allInformation.append(depthBox) print("\n") productOne = Product(nameProduct, priceProduct) discountedProductOne = DiscountedProduct(nameProduct, priceProduct, discountProduct) discountedPrice = discountedProductOne.reducing_price() allInformation.insert(3, discountedPrice) boxedProductOne = ProductBox(nameProduct, priceProduct, widthProduct, heightProduct, depthProduct) quantityProductOne = boxedProductOne.get_quantity(widthBox, heightBox, depthBox) allInformation.append(quantityProductOne) productOne.display_info() discountedProductOne.display_info() textInformation = ['Товар','Цена','Скидка','Цена со скидкой','Ширина товара (в миллиметрах)','Высота товара (в миллиметрах)','Глубина товара (в миллиметрах)','Ширина коробки (в миллиметрах)','Высота коробки (в миллиметрах)','Глубина коробки (в миллиметрах)','Количество товара в коробке'] fileName = "product_bin.bin" f.loadAndReadListInFile(fileName, allInformation, textInformation)

import lab_4.function as f import pytest @pytest.mark.parametrize("test_value,expected", [('Название', 'Название'), ('123', False), ('Name', False)]) def test_nameProduct(test_value, expected): assert f.nameProductCheck(test_value) == expected @pytest.mark.parametrize("test_value,expected", [('0', False), ('10', 10), ('Null', False)]) def test_priceProduct(test_value, expected): assert f.priceProductCheck(test_value) == expected @pytest.mark.parametrize("test_value,expected", [('0.5', False), ('99', 99), ('Null', False)]) def test_discountProduct(test_value, expected): assert f.discountProductCheck(test_value) == expected @pytest.mark.parametrize("test_value,expected", [('0.5', False), ('99', 99), ('Null', False)]) def test_sizeProduct(test_value, expected): assert f.sizeProductCheck(test_value) == expected @pytest.mark.parametrize("test_valueOne,test_valueTwo,test_valueThree,expected", [(123,[1,2],[1,2],False), ('99',[1,2],[1,2],True), ('Null',[1,2,3],[1,2],False), ('True', [1,2],'Wow',False)]) def test_file(test_valueOne, test_valueTwo, test_valueThree, expected): assert f.loadAndReadListInFile(test_valueOne, test_valueTwo, test_valueThree) == expected

Соседние файлы в предмете Программирование на Python