Python

Python Classes Examples

Python is a very popular programming language for developing different types of applications such as text-based applications, desktop applications, Web applications, etc. Python supports both structured programming and object-oriented programming. This tutorial is intended to teach how to use Python Classes by showing a real Example of Python Classes.

Some related Python classes have been used to develop the text-based “Cake Shop Application” here.

Project Features

  • Display the cake list of the shop with details
  • Add one or more cakes to the cart for purchase
  • Remove one or more cakes from the cart
  • Confirm the order
  • Cancel the order
  • Close the program

Prerequisites

  • Python 3.8+ version is required to install in the operating system to start the project work.
  • The basic knowledge of Python’s object-oriented programming will require understanding the script used in this tutorial properly.

Implementation of “Cake Shop Application”

Three classes will be used to implement the functionalities of this application. These are “shop”, “order”, and “customer”. The “shop” class is the parent class that will be used to display the application’s main menu, display the cake list of the shop, and check whether the cake selected by the user exists in the shop. The “order” class is a child class that will be created by inheriting from the “shop” class, and it will be used to add cake items into the cart, remove the cake items from the cart, and display the selected items of the cart. The “customer” class is another child class that will be created by inheriting from the “order” class, and it will be used to display the purchase details with the customer information. The following diagram shows how this simple application will work:

Store the Product Information

Any popular database server application can be attached with the Python application to store data. However, no database server has been used in this application to keep it simple, and a text file has been used to store the data. Create a text file named products.txt and add the following product information into the file before starting the next part of this application. The user will select the cake item in this file to add to the cart for purchasing. Each field is separated by a comma here:

products.txt

Id, Name,Price,Making date,expire date
01, Chocolate Cake,25, 01-06-22, 07-06-22
02, Coffee Cake,22, 02-06-22, 10-06-22
03, Vanilla Cake,30, 03-06-22, 11-06-22
04, Mud Cake,35, 02-06-22, 09-06-22
05, Straberry Cake,40,03-06-22, 12-06-22

Import the Necessary Modules

Three modules have been used in this application to generate a random number, read the current date, and create colorful text in the terminal. Create a Python file named shop.py and add the following script at the beginning of the file to import the modules. The random module will generate the order number. The date module will read the current system date. And the colored module will generate the colorful text.

#Import required modules for the shop Project
import random
from datetime import date
from colored import fg, bg, attr

Create “shop” Class

After importing the necessary modules, add the script to define the “shop” class into the shop.py file. This is the base class of this application that contains four class variables and three methods. The purpose of these variables and the methods are mentioned below.

Variables

cart_items:

It is a list variable, and it will be used to store the cake item added by the user. A new item will be appended to the list when a new cake item is selected for adding to the cart, and an existing item will be removed if the user selects a cake item for removing from the cart. This variable will be cleared after completing the purchase or canceling the purchase.

cart_amount:

It is an integer variable, and it will be used to store the sum of the product’s price added into the cart. The value of this variable will be increased when a new cake item is added to the cart, and the value of this variable will be decreased when a cake item is removed from the cart. This variable will be initialized to 0 after completing or canceling the purchase.

cust_balance:

It is an integer variable and will be used to store the cash value added by the customer. The value of this variable will be increased when the user adds the cash value, and the value of this variable will be decreased when the purchase task is completed successfully.

answer:

It is a string variable, and it will be used to take the user’s input value to do the particular task.

Methods

display_menu():

This method has been defined to show the menu list of the application. If the user types “1”, then the content of the products.txt file will be displayed. If the user types “2”, then the input prompt to take the product name will appear. If the product name provided by the user exists in the file, then the product name will be added to the cart_items list, and the price of the product will be added with cart_amount. If the user types “3”, then the application will be terminated. The fg() function has been used in the method to print the colored text in the terminal.

display_products():

This method has been defined to read the products.txt file line by line, split each line based on the comma using the split() function and store it into a list variable. Next, the list variable will be iterated using a for loop to print the file’s content in a human-readable format.

check_products():

This method has been defined to check whether the product name taken from the user exists in the products.txt file. If the product name exists in the file, then the price of that particular product will be added with the value of the cart_amount variable, and the True value will be returned from the function. The message, “The product does not exist.” will be printed if the product name does not exist in the file, and the False value will be returned from the function. This method will be called whenever a product name is taken from the user for adding to the cart.

The script of the “shop” class is provided below:

'''
'shop' class is defined here to show the main menu, display product list,
and check the product exist in the file or not
'''

class shop:
    # Declare list to store the selected product
    cart_items = []
    # Initialize the cart amount
    cart_amount = 0
    # Initialize the customer balance
    cust_balance = 0
    # Initialize the variable that will take user's input
    answer = ''

    # Define function to display the main menu
    def display_menu(self):
        print("\n%s%s%s" %(fg(150), '***Welcome to our Cake shop***', attr(0)))
        print("\n%s%s" %(fg(170), '1. Display Products...'))
        print("2. Select Product...")
        print("3. Exit")
        self.answer = input("\nType 1 or 2 or 3:")
   
    # Define function to read and display the product from the text file
    def display_products(self):
       
        print("\nThe list of products are given below:\n")
        with open('products.txt') as f:
            line = f.readline()
            # Print the header of the file
            print("Id\tName\t\tPrice\tMaking Date\tExpire Date")
            while line:
                # Initialize counter to set the space between the fields
                counter = 0
                # Read each line from the file
                line = f.readline()
                # Split each line based on the comma (,) and store in a list
                fieldList = list(line.split(","))
                print('\t')
                # Read each value from the list and print
                for val in fieldList:
                    if counter == 0:
                        space=''
                    else:
                        space='\t'
                    counter = counter + 1
                    if counter == 3:
                        val = '$' + val
                    print(val, end=space)

    # Define function to check the selected product exists in the file or not
    def check_products(self, search):

        # Open the file for reading
        with open('products.txt') as f:
            # Read each line of the file
            for line in f:
                # Split the line value based on comma(,)
                fieldList = list(line.split(","))
                for val in fieldList:
                    # Check the selected product match with the value or not
                    if search == val.strip():
                        # Add the price of the product with the cart amount if the serch value found
                        self.cart_amount = self.cart_amount + int(fieldList[2].strip())
                        return True
        # Print message if the selected product does not exist in the file
        print("The product does not exist.")
        return False

Create “order” Class

After adding the “shop” class, add the script to define the “order” class into the shop.py file. This is a child class inherited from the “shop” class that contains three methods. The purpose of these methods is mentioned below.

Methods

add_to_cart():

This method has been defined to add the product name into the cart_items list if the product exists in the products.txt file and print a message after adding the product into the cart. This method will be called when the user selects the second option (“Select Product…”) of the main menu by typing “2” or the first option of the second menu (“Add Product”) by typing “1”.

remove_from_cart():

This method has been defined to remove the product from the cart_items list if the product name taken from the user exists in the cart_items. This method will be called when the user selects the second option of the second menu (“Remove Product”) by typing “2”. After removing the product, the price of the removed product will be deducted from the cart_amount variable. “The product does not exist in the cart.” message will be printed if the product name taken from the user does not exist in the cart_items list.

display_cart():

This method has been defined to display the content of the cart_items list, the value of the cart_amount, and the second menu items to add product or remove the product or confirm payment or cancel the purchase. If the cart_items list is empty, then the message, “Your cart is empty.” will be displayed. This method will be called when the task of adding a product or removing a product is completed. This method will return the values of the cart_items list if the cart is not empty or return 0 if the cart is empty.

The script of the “order” class is provided below:

'''
'order' class is defined to add product into the cart, remove product
from the cart, and display the cart item
'''

class order(shop):

    # Define function to add product into the cart
    def add_to_cart(self, item):
        # Add product into the cart
        self.cart_items.append(item)
        print("%s is added in the cart." %(item))

    # Define function to remove product from the cart
    def remove_from_cart(self, obj):
        item = input("Enter the product name:")
        if item in obj.cart_items:
            # Remove product from the cart
            obj.cart_items.remove(item)
            print("Product is removed from the cart")
            # Open the file to search the price of the product
            with open('products.txt') as f:
                for line in f:
                    fieldList = list(line.split(","))
                    for val in fieldList:
                        if item == val.strip():
                            # Remove the price of the removed product from the cart amount
                            obj.cart_amount = obj.cart_amount - int(fieldList[2].strip())  
        else:
            print("Product does not exist in the cart.")
       
    # Define function to display the cart items
    def display_cart(self, obj):
        # Check the cart amount to find out the cart is empty or not
        if obj.cart_amount > 0:
            # Display the added cart items
            print("\nYou have added the following item(s) in your cart:\n")
            for val in self.cart_items:
                print(val)
           
            # Print the total cart amount
            print("\n%s%s%d%s"  %(fg(25), 'Total amount:$', obj.cart_amount, attr(0)))

            # Display the second menu
            print("\n1. Add Product")
            print("2. Remove Product")
            print("3. Confirm Payment")
            print("4. Cancel")
            ans = input("\nType 1 or 2 or 3 or 4:")
            return ans

        else:
            # Print message if the cart is empty
            print("You cart is empty.")
            return 0

Create “customer” Class

After adding the “order” class, add the script to define the “customer” class into the shop.py file. This is another child class inherited from the “order” class containing the constructor method and a user-defined method. The purpose of these methods is mentioned below.

Methods:

Constructor Method

The constructor method is defined by __init__(). Suppose the user selects the third option of the second menu (“Confirm Payment”). In that case, the constructor of the “customer” class will be called to initialize the customer information at the time of object creation of the “customer” class and compete for the purchase task. This method will take four arguments. These are name, address, phone, and cash.

purchase_info():

This method has been defined to display the purchase details containing the order number, order date, customer’s name, customer’s address, customer’s phone, list of purchased products, and total price of all purchased products. Here, the order number will be generated using the random() function. This method will be called if the cash value added by the user is more than or equal to the value of the cart_amount variable.

The script of the “customer” class is provided below:

'''
'customer' class id defined to display the purchase information
after confirming the payment
'''

class customer(order):

    # Define constructor to initialize the customer information
    def __init__(self, name, address, phone, cash):
        name = name
        address = address
        contact_no = phone
        add_cash = cash

    # Define function to display the purchase information with customer details
    def purchase_info(self,obj):
        # Gnerate a random order number
        order_no = random.random()*100000000
        order_no = round(order_no)
        # Initilize the order date
        today = date.today()
        order_date = today.strftime("%B %d, %Y")

        # Print purchase information
        print("\nYour purchase information is given below:\n")
        print("Order No            :%s" %order_no)
        print("Order Date          :%s" %order_date)
        print("Customer's name     :%s" %name)
        print("Customer's address  :%s" %address)
        print("Customer's phone no :%s" %contact_no)

        # Print purchased product information
        print("\nPurchased product list:\n")
        for val in self.cart_items:
           print(val)
        print("\n%s%s%d%s"  %(fg(25), 'Total amount:$', obj.cart_amount, attr(0)))
        print("Thank you.")

Create Objects

After defining the necessary classes of application, add the script to create objects for using the class variables and call the methods to complete the implementation of the “Cake Shop Application”. At first, the object of the “shop” class will be defined, and the display_menu() method will be called by using this object for displaying the main menu. In the script, the first infinite loop has been used to display the main menu at the start of the application and after confirming or canceling the purchase. This loop will be terminated, and the application will be closed when the user selects the third option (“Exit”) of the main menu. The second infinite loop has been used to add the products into the cart until the user types “none” and displays the second menu after adding or removing a product into the cart. This loop will be terminated if the user selects the third (“Confirm Payment”) or fourth (“Cancel”) option of the second menu. Suppose the user selects the third option of the second menu and the cash amount added by the user is less than the cart_amount value. Then the second menu will appear again by displaying the message, “You have not enough balance.”. Both cart_items and cart_amount values will be cleared after terminating the second infinite loop to make the next purchase. The script of this part is provided below:

# Declare object of the 'shop' class
objShop = shop()
# Declare the infinite loop to display the menu repeatedly
# until the user presses '3'
while True:
    # Display the main menu
    objShop.display_menu()
    # Set initial value for the remove_item
    remove_item = False
   
    # Display the main menu if the user presses '1'
    if objShop.answer == '1':
        objShop.display_products()
    # Display the purchase option if the user presses '2'
    elif objShop.answer == '2':
        # Declare object of the 'order' class
        objOrder = order()
       
        # Declare the infinite loop to display the second menu repeatedly
        # until the user presses '3' or '4'
        while True:
            # Take the product name to add into the cart if the value of remove_item is False
            if remove_item == False:
                item = input("\nType the product name:")
            if item == 'none' :
                # Display the cart after adding or removing the product
                return_val = objOrder.display_cart(objShop)
                # Terminate from the loop if the cart is empty
                if return_val == 0:
                    break
                elif return_val == '1':
                    item = input("Type the product name:")
                    # Check the product exists in the products.txt file or not
                    pro_exist = objShop.check_products(item)
                    # Add the products into the cart if the product exists
                    if pro_exist == True:
                        objOrder.add_to_cart(item)
                    remove_item = False
                   
                elif return_val == '2':
                    # Remove the selected product from the cart
                    return_val = objOrder.remove_from_cart(objShop)
                    remove_item = True
                   
                elif return_val == '3':
                    # Take customer's information
                    name = input("Enter your name:")
                    address = input("Enter your address:")
                    contact_no = input("Enter your contact number:")
                    cash = int(input("Add cash: $"))
                    # Add the cash value with the customer's current balance
                    objShop.cust_balance = objShop.cust_balance + cash

                    # Check the balance of the customer is less than the cart amount ot not
                    if objShop.cust_balance < objShop.cart_amount:
                        print("You have not enough balance.")
                    else:
                        # Create object of the 'customer' class
                        objCustomer = customer(name, address, contact_no, cash)
                        # Print the purchase information
                        objCustomer.purchase_info(objShop)
                        # Deduct the purchase amount from the customer's balance
                        objShop.cust_balance = cash - objShop.cart_amount                  
                    break
                else:
                    # Print message if the customer cancels the purchase
                    print("You have cancelled your purchase.")
                    break
            else:
                # Add the products into the cart if the product exists
                pro_exist = objShop.check_products(item)
                if pro_exist == True:
                     objOrder.add_to_cart(item)
                print("Type 'none' to stop adding product")
        # Clear the cart list after purchased or cancelled
        objShop.cart_items.clear()
        # Clear the cart amount after purchased or cancelled
        objShop.cart_amount = 0    
    # Terminate from the application if the users presses '3'
    elif objShop.answer == '3':
        print("\nTerminated from the application.")
        exit()

Application Output

After adding all the scripts into the shop.py file serially, you can check whether the application is working correctly or not. The way of using this application has been shown in this part of the tutorial.

Run the Application

At first, the user has to open the terminal and go to the location where the products.txt and shop.py files are located. You must store these files in the same location to get the output correctly. Run the following command to execute the application:

$ python3 shop.py

The following output will appear after executing the previous command. This is the main menu of this application. The user can select any of the three options shown in the output by typing “1” or “2” or “3”. The list of the products will be displayed if the user types, “1”. The input prompt to take the product name will appear if the user types, “2”. The application will be closed if the user types, “3”. The menu will appear again if the user types any other character.

Display Products

The following output will appear if the user types “1”. The content of the products.txt file has been shown in this output. The user can select any cake names shown in the output to add to the cart, and the user has to select the menu’s second option to do the task.

Add Product Into the Cart by Using the Main Menu

Two ways exist in the application to add the product to the cart. The first way is to select the second option on the main menu. The following output will appear if the user typed “2”. The user must type the name of any cake item that exists in the file to add it to the cart.

The following output will appear if the user types “Mud Cake” that exists in the product list. The output shows that the product has been added to the cart, and the user can add another product by typing the product name again. If the user does not want to add any product, then they must type “none”.

The following output will appear if another product named “Coffee Cake” is added:

The following output will appear if the value “none” is typed as the input value. The list of the cart items is shown in the output. Two cake items have been added: “Mud Cake” and “Coffee Cake”. The price of the “Mud Cake” is $35 and the “Coffee Cake” is $22. The total price of the cakes is $35+$22 = $57, shown in the output. The second menu was displayed after displaying the cart information. The user can add products, remove products, purchase the products added to the cart, and cancel the purchase using this menu:

Add Product Into the Cart by Using the Second Menu

The following output will appear if the user typed “2”. The user needs to type the name of any cake item that exists in the file to add it to the cart.

The following output will appear after typing “Vanilla Cake” as the input value. The user can add more items to the cart by typing the product name again. If the user does not want to add more products, then they must type “none” to stop adding the product to the cart.

The following output will appear after typing “none” as the input value. The output shows that the new product “Vanilla Cake” has been added to the cart, and the price of the “Vanilla Cake” has been added with the cart amount. So, the total amount is now $57 + $30 = $87. The second menu has appeared again. The purpose of this menu has been explained previously.

Remove the Product From the Cart

The following output will appear if the user types “2” as the input value. The user must type the name of any cake item that exists in the cart to remove it from the cart. If the user types any value that does not exist in the cart, then an error message will be printed.

The following output will appear if the user types “Chocolate Cake” as an input value that exists in the products.txt file but does not exist in the cart. So, the error message, “Product does not exist in the cart.“, has appeared in the output, and no item has been added or removed from the cart. The total amount value of the cart has not changed also.

The following output will appear if the user types, “Coffee Cake” as the input value that exists in the cart. The success message, “Product is removed from the cart”, has been printed. The output also shows that “Coffee Cake” has been removed from the cart, and the price value of this item has been deducted from the cart amount value. The price of the “Coffee Cake” is $22. So, the total amount of the cart is now $87 – $22 = $65.

The following output will appear if all items from the cart are removed. The output shows two messages. One is to remove the last product, and another is to inform the user that the cart is now empty. Since there is no product in the cart, the second menu has been gone, and the main menu has appeared again.

Make Payment

The third option of the second menu is used to confirm the purchase by adding the customer’s information and the cart amount value. The following output will appear if the user types “3” to select the third option of the second menu after adding some cake items to the cart. The output shows that two cake items are added to the cart, and the total price of the cakes is $60. The input prompt to take the customer’s name has appeared after typing the value, “3”. Next, other input prompts will appear to add other information related to the customer and the cash amount to purchase the product.

In the following output, the customer’s name, address, phone number, and the cash amount have been added. But the added cash value is less than the total price of the products. The total cart amount was $60, and $45 has been added as the cash value. The message, “You have not enough balance.” has appeared for this reason, and the order was canceled by making the cart empty. The main menu has appeared again.

The following output will appear if the cash added by the user is equal to or more than the total amount of the cart. Here, the cart’s total price is $35, and the user added $100 as the cash value, which is greater than the total price. The output also shows that a random number has been generated as the order number, and the current system date has been printed as the order date. The main menu has appeared again for the next purchase. The current balance of the user is $100 – $35 = $65. If the same user again purchases any cake item from the shop, then the purchase amount will be deducted from the user’s current balance.

The following output will appear if the user purchases again and the purchase amount is less than their current balance. According to the output, two cake items have been added to the cart and the total price of the cakes is $47. The user added $0 cash, but the customer’s current balance is $65. So, the payment has been completed successfully, and the “Thank you” message has been printed. The current balance of the user is $65 – $47 = $18.

If the same user again adds an item to the cart and the total price of the item is less than the current balance of the user, then the following output will appear. The user’s current balance is $18 after the last transaction, but the product’s total price is $30. So, the message, “You have not enough balance.” has been printed and the order has been canceled by making the cart empty.

The following output will appear if the user adds $12 with the $18 to purchase the “Vanilla Cake” of $30. The current balance of the user is $0 after the purchase.

Cancel Payment

The user can cancel the order after adding items to the cart by selecting the fourth option of the second menu or by removing all items from the cart. The following output will appear if the user selects the fourth option of the second menu by typing “4”. The message, “You have canceled your purchase.” has been printed for canceling the order. The way to cancel the order by removing all items from the cart has been shown before. The main menu will be appeared after canceling the order.

Close the Application

The application can be closed by selecting the third option on the main menu. The following output will appear if the user types “3” to close the application. The application has been terminated by the message, “Terminated from the application”.

Limitations of This Application

The way of implementing a very simple text-based application by Python classes has been shown in this tutorial. But this application has some limitations, which are mentioned below:

  • No order or customer information is stored permanently. The application needs to keep records of the previous sales. Two more text files can be created to store the order and the customer information.
  • No stock record is maintained in this application which is an important part of the shop application. If any product is out of stock, then a message should be passed to the user.
  • If the user adds the same product multiple times, then each product will be added separately, which is inefficient. It is essential to count the number of each product in the cart if the same product is added multiple times.
  • There is no option to remove all items from the cart by single command without canceling the order. The user has to remove each item separately to make the cart empty.
  • The remaining customer balance does not display after completing the payment of the order. It will help the user to add cash for the next order.

***The readers of this tutorial will try to implement the features mentioned above to develop their programming skills and make the application more efficient for learning.

Video Tutorial on This Topic

Conclusion

The guidelines to implement a simple text-based Python application have been provided in this tutorial for novice Python users. The basic features of the shop application are used to implement in this tutorial, such as product list, add to cart, remove from the cart, payment system, and cancel payment. For simplicity, we used the text file here to store the data permanently. But any standard database application, such as SQLite and MySQL, can be used to manage the application data more efficiently.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.