Advertisement
pacho_the_python

Untitled

Sep 14th, 2022
687
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. class ShoppingCart:
  2.     def __init__(self, shop_name: str, budget: float):
  3.         self.shop_name = shop_name
  4.         self.budget = budget
  5.         self.products = {}
  6.  
  7.     @property
  8.     def shop_name(self):
  9.         return self.__shop_name
  10.  
  11.     @shop_name.setter
  12.     def shop_name(self, value: str):
  13.         if not value[0].isupper() or not value.isalpha():
  14.             raise ValueError("Shop must contain only letters and must start with capital letter!")
  15.         self.__shop_name = value
  16.  
  17.     def add_to_cart(self, product_name: str, product_price: float):
  18.         if product_price >= 100.0:
  19.             raise ValueError(f"Product {product_name} cost too much!")
  20.         self.products[product_name] = product_price
  21.         return f"{product_name} product was successfully added to the cart!"
  22.  
  23.     def remove_from_cart(self, product_name: str):
  24.         if product_name in self.products:
  25.             del self.products[product_name]
  26.             return f"Product {product_name} was successfully removed from the cart!"
  27.         else:
  28.             raise ValueError(f"No product with name {product_name} in the cart!")
  29.  
  30.     def __add__(self, other):  # other is another ShoppingCart instance
  31.         new_shop_name = f"{self.shop_name}{other.shop_name}"
  32.         new_budget = self.budget + other.budget
  33.         new_shopping_cart = ShoppingCart(new_shop_name, new_budget)
  34.         new_shopping_cart.products.update(**self.products)
  35.         new_shopping_cart.products.update(**other.products)
  36.         return new_shopping_cart
  37.  
  38.     def buy_products(self):
  39.         total_sum = sum(self.products.values())
  40.         if total_sum > self.budget:
  41.             raise ValueError(f"Not enough money to buy the products! Over budget with {total_sum - self.budget:.2f}lv!")
  42.         return f'Products were successfully bought! Total cost: {total_sum:.2f}lv.'
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement