Python classes basics - Creating a food menu
This is an example to illustrate the basics of Python classes. We will use classes to create an elementary food ordering menu.
Python classes do not require a constructor like in C or C++. A class can be created without one. Let's create a class MenuItem with nothing in it. We use pass
for empty classes.
class MenuItem:
pass
Let's create an instance of the class MenuItem called menu_item1.
menu_item1 = MenuItem()
Let's create some attributes to this menu_item1 intance like name and price. Notice that this can be done without declaring the attributes in the class.
menu_item1.name = 'Sandwich'
print(menu_item1.name)
menu_item1.price=5
print(menu_item1.price)
Let's create another instance of the class MenuItem and assign some variables to it.
# Create an instance of the MenuItem class
menu_item2 = MenuItem()
# Set the name of menu_item2 to 'Chocolate Cake'
menu_item2.name = 'Chocolate Cake'
# Output the name of menu_item2
print(menu_item2.name)
# Set the price of menu_item2 to 4
menu_item2.price = 4
# Output the price of menu_item2
print(menu_item2.price)
Methods are functions within classes. Let's create a method info to print something. All methods need to be passed the argument self.
class MenuItem:
# Define the info method
def info(self):
print('Display menu item name and price')
menu_item1 = MenuItem()
menu_item1.name = 'Sandwich'
menu_item1.price = 5
# Call the info method from menu_item1
menu_item1.info()
menu_item2 = MenuItem()
menu_item2.name = 'Chocolate Cake'
menu_item2.price = 4
# Call the info method from menu_item2
menu_item2.info()
Let's modify the method to print specific information about instances like their names and prices.
class MenuItem:
def info(self):
# Output in the format '____: $____'
print(self.name+': $'+str(self.price))
menu_item1 = MenuItem()
menu_item1.name = 'Sandwich'
menu_item1.price = 5
menu_item1.info()
menu_item2 = MenuItem()
menu_item2.name = 'Chocolate Cake'
menu_item2.price = 4
menu_item2.info()
We can also return values from class methods just like any other function.
class MenuItem:
def info(self):
# Return the contents of print() as a return value
return self.name + ': $' + str(self.price)
menu_item1 = MenuItem()
menu_item1.name = 'Sandwich'
menu_item1.price = 5
# Output the value of menu_item1.info()
print(menu_item1.info())
menu_item2 = MenuItem()
menu_item2.name = 'Chocolate Cake'
menu_item2.price = 4
# Output the value of menu_item2.info()
print(menu_item2.info())
Let's pass arguments to methods and perform basic calculations like calculating the total price of the order. Note that the first argument must always be self.
class MenuItem:
def info(self):
return self.name + ': $' + str(self.price)
# Define the get_total_price method
def get_total_price(self,count):
total_price=self.price*count
return total_price
menu_item1 = MenuItem()
menu_item1.name = 'Sandwich'
menu_item1.price = 5
print(menu_item1.info())
# Call the get_total_price method
result=menu_item1.get_total_price(4)
# Output 'Your total is $____'
print('Your total is $'+str(result))
As mentioned earlier, Python does not require a constructor to be created and we have come so far without it. However, Python has a special function called __init__
that is called each time an instance is created. __init__
is optional and can be used when we need something to be done every time an instance is created.
class MenuItem:
# Define the __init__ method
def __init__(self):
print('An instance of the MenuItem class was created!')
def info(self):
return self.name + ': $' + str(self.price)
def get_total_price(self, count):
total_price = self.price * count
return total_price
menu_item1 = MenuItem()
menu_item1.name = 'Sandwich'
menu_item1.price = 5
print(menu_item1.info())
result = menu_item1.get_total_price(4)
print('Your total is $' + str(result))
For example, let's give a default name and price to an instance when it's created.
class MenuItem:
def __init__(self):
# Set self.name to 'Sandwich'
self.name='Sandwich'
# Set self.price to 5
self.price=5
def info(self):
return self.name + ': $' + str(self.price)
def get_total_price(self, count):
total_price = self.price * count
return total_price
menu_item1 = MenuItem()
print(menu_item1.info())
result = menu_item1.get_total_price(4)
print('Your total is $' + str(result))
However, now every instance has the same name and price. We would like to create intances of food items with different names and prices. Let's do that by passing arguments to the __init__
function.
class MenuItem:
# Add the parameters name and price
def __init__(self,name,price):
# Set this to the name argument instead of 'Sandwich'
self.name = name
# Set this to the price argument instead of 5
self.price = price
def info(self):
return self.name + ': $' + str(self.price)
def get_total_price(self, count):
total_price = self.price * count
return total_price
menu_item1 = MenuItem('Sandwich', 5)
menu_item2 = MenuItem('Chocolate Cake', 4)
menu_item3 = MenuItem('Coffee', 3)
menu_item4 = MenuItem('Orange Juice', 2)
# Set the menu_items variable to a list of the MenuItem instances
menu_items=[menu_item1, menu_item2, menu_item3, menu_item4]
# Create the for loop
for menu_item in menu_items:
print(menu_item.info())
Let's print them with index numbers to make it easier for customers to order.
index=0
for menu_item in menu_items:
# Print out in the format '0. Sandwich: $5' for each index
print(str(index)+'. '+menu_item.info())
# Add 1 to the index variable
index+=1
Looks almost ready. Let's use the input
function to take orders from customers and confirm their order.
# Receive input from the console and assign the order variable to it
order=int(input('Enter menu item number: '))
# Set the selected_menu variable to the menu item that was selected
selected_menu=menu_items[order]
# Output 'Selected item: ____'
print('Selected item: '+selected_menu.name)
Customers might like to order more than one quantity. Let's add an option to take quantity as an input as well. Also, make it more interesting by throwing in a discount if three or more are ordered.
class MenuItem:
def __init__(self, name, price):
self.name = name
self.price = price
def info(self):
return self.name + ': $' + str(self.price)
def get_total_price(self, count):
total_price = self.price * count
# If count is 3 or higher, multiply it by 0.9
if count>=3:
total_price=total_price*0.9
# Round total_price to the nearest whole number and return it
return round(total_price)
menu_item1 = MenuItem('Sandwich', 5)
menu_item2 = MenuItem('Chocolate Cake', 4)
menu_item3 = MenuItem('Coffee', 3)
menu_item4 = MenuItem('Orange Juice', 2)
menu_items = [menu_item1, menu_item2, menu_item3, menu_item4]
index = 0
for menu_item in menu_items:
print(str(index) + '. ' + menu_item.info())
index += 1
print('--------------------')
order = int(input('Enter menu item number: '))
selected_menu = menu_items[order]
print('Selected item: ' + selected_menu.name)
# Receive input from the console and set the count variable to it
count=int(input('Enter quantity (10% off for 3 or more): '))
# Call the get_total_price method
result=selected_menu.get_total_price(count)
# Output 'Your total is $____'
print('Your total is $'+str(result))
We have succesfully used Python classes to create a very basic food ordering system. The code can be split into multiple files if it's getting too long or if there are multiple people or groups working on different things. For example, the MenuItem class can be moved to a seperate file called menu_item.py and be imported into the main script when needed. Specific classes from this seperate file can be called directly too instead of importing the whole file.
# Importing the MenuItem class from menu_item.py
from menu_item import MenuItem
menu_item1 = MenuItem('Sandwich', 5)
menu_item2 = MenuItem('Chocolate Cake', 4)
menu_item3 = MenuItem('Coffee', 3)
menu_item4 = MenuItem('Orange Juice', 2)
menu_items = [menu_item1, menu_item2, menu_item3, menu_item4]
index = 0
for menu_item in menu_items:
print(str(index) + '. ' + menu_item.info())
index += 1
print('--------------------')
order = int(input('Enter menu item number: '))
selected_menu = menu_items[order]
print('Selected item: ' + selected_menu.name)
# Receive input from the console and set the count variable to it
count=int(input('Enter quantity (10% off for 3 or more): '))
# Call the get_total_price method
result=selected_menu.get_total_price(count)
# Output 'Your total is $____'
print('Your total is $'+str(result))
An improvement to the above example using inheritence is demostrated here.
Note: The code on this page is something that I wrote when I took Progate's free Python classes.
Last updated 2020-12-01 12:11:36.372057 IST
Comments