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.
Output:
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.