class Product():
def __init__(self, name, weight, category):
self.name = name
self.weight = weight
self.category = category
def __str__(self):
return f'{self.name}, {self.weight}, {self.category}'
class Shop():
def __init__(self):
self.products = []
def add(self, product):
for p in self.products:
if p.name == product.name:
print(f'Продукт {product.name} уже есть в магазине')
return
self.products.append(product)
def __str__(self):
return '\n'.join(str(p) for p in self.products)
s1 = Shop()
p1 = Product('Potato', 50.5, 'Vegetables')
p2 = Product('Spaghetti', 3.4, 'Groceries')
p3 = Product('Potato', 5.5, 'Vegetables')
s1.add(p2)
s1.add(p3)
s1.add(p1)
print(s1)
from typing import List
from string import punctuation
punct = set(punctuation)
class Product:
def __init__(self, name: str, weight: float, category: str):
self.name = name
self.weight = weight
self.category = category
def __str__(self):
return f'{self.name}, {self.weight}, {self.category}\n'
class Shop:
def __init__(self):
self._file_name = 'products.txt'
self.product_names = {*map(lambda p: p.name, self.get_products())}
def get_products(self) -> List[Product]:
with open(self._file_name, encoding='UTF-8', mode='r') as f:
product_list = []
for l in f.readlines():
product_param = l.split()
for i in range(len(product_param)):
product_param[i] = ''.join(
filter(lambda x: x not in punct,
product_param[i]))
product_param[1] = float(product_param[1])
product_list.append(Product(*product_param))
return product_list
def add(self, *products: Product) -> None:
with open(self._file_name, encoding='UTF-8', mode='a') as f:
for p in products:
if p.name not in self.product_names:
f.write(str(p))
else:
print(f'Продукт {p.name} уже есть в магазине')
class Product():
def __init__(self, name, weight, category):
self.name = name
self.weight = weight
self.category = category
def __str__(self):
return f'{self.name}, {self.weight}, {self.category}\n'
class Shop():
def __init__(self):
self.__file_name = 'products.txt'
def get_products(self):
file = open(self.__file_name, 'r')
data = file.read()
file.close()
return data
def add(self, *products):
for product in products:
if product.name not in products:
file = open(self.__file_name, 'a')
file.write(product.__str__())
file.close()
elif product.name in products:
print(f'Продукт {product.name} уже есть в магазине')
s1 = Shop()
p1 = Product('Potato', 50.5, 'Vegetables')
p2 = Product('Spaghetti', 3.4, 'Groceries')
p3 = Product('Potato', 5.5, 'Vegetables')
print(p2) # __str__
s1.add(p1, p2, p3)
print(s1.get_products())
добавляются объекты в файл и проверка не выполняется