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
- 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.
- The class also has three methods:
- 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.
- 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.
- The calculate_total_cost method returns the self.total_cost, representing the total cost of the items in the cart.
- The code creates an object cart of the ShoppingCart class by calling its constructor without any arguments.
- 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.
- The remove_item method is called on the cart object to remove the “Shirt” item with a cost of 250.
- 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.
- Finally, the contents of the cart are printed using cart.items, and the total cost is printed using total_cost.
- 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 Animal with attributes name and color.
Create a Python class called Dog that inherits from the Animal class.
Python oops program to create a class with the constructor.
Python oops program to create a class with an instance variable.
Python oops program to create a class with Instance methods.
Python oops program to create a class with class variables.