Advertisement
furas

Python - class Product and Inventory

Jul 8th, 2018
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. class Product(object):
  2.  
  3.     def __init__(self, price, _id, quantity):
  4.         self.price = price
  5.         self.id = _id
  6.         self.quantity = quantity
  7.  
  8.     def total_value(self):
  9.         return self.price * self.quantity
  10.  
  11.     def __str__(self):
  12.         return 'id: {} price: {} quantity: {} value: {}'.format(self.id, self.price, self.quantity, self.total_value())
  13.  
  14.     #def __len__(self):
  15.     #    return self.quantity
  16.  
  17.  
  18. class Inventory(object):
  19.  
  20.     _products = list()
  21.  
  22.     def append(self, product):
  23.         self._products.append(product)
  24.  
  25.     def total_value(self):
  26.          return sum(item.total_value() for item in self._products)
  27.  
  28.     def total_products(self):
  29.          return len(self._products)
  30.  
  31.     def total_quantity(self):
  32.         return sum(item.quantity for item in self._products)
  33.  
  34.     def __str__(self):
  35.         return '\n'.join(str(item) for item in self._products)  
  36.  
  37.     #def __len__(self):
  38.     #    return sum(len(item) for item in self._products)
  39.     #    return sum(item.quantity for item in self._products)
  40.  
  41.  
  42. inv = Inventory()
  43.        
  44. inv.append( Product(300, 'cellphone', 12) )
  45. inv.append( Product(8000, 'laptop', 6) )
  46. inv.append( Product(2, 'sd card', 1234) )
  47.  
  48. print('Available products:')
  49. print(inv)
  50.  
  51. print('Number of products:', inv.total_products())
  52. print('Total quantity:', inv.total_quantity())
  53. print('Total value:', inv.total_value())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement