46. Problem to create a Python class example

In this Python oops program, we will create a Python class example. Python class called ShoppingCart with attributes items and total_cost.

Python class example

Steps to solve the program
  1. The ShoppingCart class has a constructor method __init__ that initializes two instance variables: self.items as an empty list to store the items in the cart, and self.total_cost as 0 to track the total cost of the items.
  2. The class also has three methods:
  3. The add_item method takes item and cost as parameters and appends the item to the self.items list and adds the cost to the self.total_cost.
  4. The remove_item method takes item and cost as parameters and removes the item from the self.items list if it exists and subtracts the cost from the self.total_cost.
  5. The calculate_total_cost method returns the self.total_cost, representing the total cost of the items in the cart.
  6. The code creates an object cart of the ShoppingCart class by calling its constructor without any arguments.
  7. The add_item method is called three times on the cart object to add three items: “Shirt” with a cost of 250, “Pants” with a cost of 500, and “Shoes” with a cost of 1000.
  8. The remove_item method is called on the cart object to remove the “Shirt” item with a cost of 250.
  9. The calculate_total_cost method is called on the cart object to calculate the total cost of the items in the cart, and the result is assigned to the total_cost variable.
  10. Finally, the contents of the cart are printed using cart.items, and the total cost is printed using total_cost.
  11. Thus, we have created Python class example.
				
					class ShoppingCart:
    def __init__(self):
        self.items = []
        self.total_cost = 0
    
    def add_item(self, item, cost):
        self.items.append(item)
        self.total_cost += cost
    
    def remove_item(self, item, cost):
        if item in self.items:
            self.items.remove(item)
            self.total_cost -= cost
    
    def calculate_total_cost(self):
        return self.total_cost

# Create an object of the ShoppingCart class
cart = ShoppingCart()
cart.add_item("Shirt", 250)
cart.add_item("Pants", 500)
cart.add_item("Shoes", 1000)
cart.remove_item("Shirt", 250)
total_cost = cart.calculate_total_cost()
print("Items in cart:", cart.items)
print("Total Cost:", total_cost)
				
			

Output:

				
					Items in cart: ['Pants', 'Shoes']
Total Cost: 1500
				
			

Related Articles

Create a Python class called EBook that inherits from the Book class.

Create a Python class called Animal with attributes name and color.

Leave a Comment