Как реализовать логику для удаления продуктов из корзины с помощью метода sub из 2 словарей
Подскажите, как лучше написать код. Необходимо реализовать логику для удаления продуктов из корзины с помощью магического метода sub из 2 словарей.
class Products:
def __init__(self, products, bonuses=0):
self.bonuses = bonuses
self.products = products
def get_products_price(self):
return sum(self.products.values()) - self.bonuses
def __add__(self, other):
if isinstance(other, int):
return Products(self.products, self.bonuses + other)
elif isinstance(other, Products):
new_products = {}
for product, price in self.products.items():
if product not in new_products:
new_products[product] = price
for product, price in other.products.items():
if product not in new_products:
new_products[product] = price
return Products(new_products)
Ответы (1 шт):
Автор решения: Ihar PSY
→ Ссылка
def __sub__(self, other):
new_products = {}
for product, price in self.products.items():
if product not in other.products:
new_products[product] = price
return Products(new_products)
def __rsub__(self, other):
if isinstance(other, int):
return Products(self.products, self.bonuses - other)