Python 类示例
在这里,一些相关的Python类被用来开发基于文本的“蛋糕店应用程序”。
项目特点
- 显示商店的蛋糕清单及详细信息
- 将一个或多个蛋糕添加到购物车以进行购买
- 从购物车中移除一个或多个蛋糕
- 确认订单
- 取消订单
- 关闭程序
先决条件
- 需要安装 Python 3.8 及以上版本的操作系统才能开始项目工作。
- 要正确理解本教程中使用的脚本,需要掌握Python面向对象编程的基本知识。
“蛋糕店应用程序”的实施
将使用三个类来实现此应用程序的功能。这些是“商店”、“订单”和“客户”。“商店”类是父类,将用于显示应用程序的主菜单、显示商店的蛋糕列表,以及检查用户所选的蛋糕是否存在于商店中。“订单”类是一个子类,将通过继承“商店”类来创建,并将用于将蛋糕项目添加到购物车中、从购物车中移除蛋糕项目,以及显示购物车中选择的项目。 “客户”类是另一个子类,将通过继承“订单”类来创建,它将用于显示带有客户信息的购买细节。下面的图示展示了这个简单应用的工作原理:
存储产品信息
任何流行的数据库服务器应用程序都可以与 Python 应用程序连接以存储数据。然而,为了简单起见,本应用程序没有使用任何数据库服务器,而是使用文本文件来存储数据。在开始本应用程序的下一部分之前,创建一个名为products.txt的文本文件,并将以下产品信息添加到文件中。用户将在此文件中选择蛋糕项以添加到购物车以进行购买。这里每个字段由逗号分隔:
产品.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导入必要的模块
在这个应用程序中使用了三个模块来生成随机数、读取当前日期和在终端中创建彩色文本。创建一个名为shop.py的Python文件,并在文件开头添加以下脚本以导入这些模块。random模块将生成订单号。date模块将读取当前系统日期。而colored模块将生成彩色文本。
#Import required modules for the shop Project
import random
from datetime import date
from colored import fg, bg, attr创建“商店”类
在导入必要的模块后,将定义shop类的脚本添加到shop.py文件中。这是该应用程序的基类,包含四个类变量和三个方法。以下是这些变量和方法的目的。
变量
购物车商品:
这是一个列表变量,用于存储用户添加的蛋糕项目。当用户选择添加新蛋糕项目到购物车时,将新的项目附加到列表中;如果用户选择从购物车中移除蛋糕项目,则会移除现有项目。完成购买或取消购买后,该变量将被清空。
购物车金额:
这是一个整数变量,它将用于存储添加到购物车中的产品价格的总和。当有新的蛋糕项目添加到购物车时,变量的值将增加;当从购物车中移除蛋糕项目时,变量的值将减少。在完成或取消购买后,该变量将初始化为0。
客户余额:
它是一个整数变量,将用于存储客户添加的现金值。当用户添加现金值时,此变量的值将增加,而当购买任务成功完成时,此变量的值将减少。
答案 :
这是一个字符串变量,将用于获取用户的输入值以执行特定任务。
方法
显示菜单():
该方法已被定义以显示应用程序的菜单列表。如果用户输入“1”,那么products.txt文件的内容将被显示。如果用户输入“2”,则将出现输入提示以获得产品名称。如果用户提供的产品名称在文件中存在,产品名称将被添加到cart_items列表中,产品的价格将与cart_amount相加。如果用户输入“3”,则应用程序将被终止。该方法中使用了fg()函数,以在终端中打印彩色文本。
显示产品():
此方法已被定义为逐行读取products.txt文件,使用split()函数基于逗号分割每一行,并将其存储到列表变量中。接下来,将使用for循环迭代列表变量,以人类可读的格式打印文件内容。
检查产品():
此方法已定义用于检查用户提供的产品名称是否存在于products.txt文件中。如果产品名称存在于文件中,则该产品的价格将与cart_amount变量的值相加,并且函数将返回True值。如果产品名称在文件中不存在,则将打印消息“该产品不存在。”,并且函数将返回False值。每当用户提供产品名称以添加到购物车时,将调用此方法。
下面提供了商店类的脚本:
'''
'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创建“订单”类
在添加了“shop”类后,将脚本添加到shop.py文件中以定义“order”类。这个子类是从“shop”类继承的,包含三个方法。这些方法的目的如下所述。
方法
添加到购物车():
此方法已定义为如果产品存在于products.txt文件中,则将产品名称添加到cart_items列表中,并在将产品添加到购物车后打印消息。当用户通过输入“2”选择主菜单的第二个选项(“选择产品...”)或通过输入“1”选择第二个菜单的第一个选项(“添加产品”)时,将调用此方法。
从购物车移除:
该方法已被定义为从cart_items列表中移除产品,如果用户输入的产品名称存在于cart_items中。当用户在第二个菜单中选择第二个选项(“移除产品”)并输入“2”时,将调用该方法。在移除产品后,将从cart_amount变量中扣除被移除产品的价格。如果用户输入的产品名称在cart_items列表中不存在,将打印“该产品在购物车中不存在。”的信息。
显示购物车()
该方法已被定义用于显示cart_items列表的内容、cart_amount的值以及添加产品、移除产品、确认支付或取消购买的第二个菜单项。如果cart_items列表为空,则将显示消息“您的购物车是空的。”当添加产品或移除产品的任务完成时,将调用该方法。如果购物车不为空,该方法将返回cart_items列表的值;如果购物车为空,则返回0。
下面提供了订单类的脚本:
'''
'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创建“客户”类
在添加了“order”类之后,将脚本添加到shop.py文件中以定义“customer”类。这是从“order”类继承的另一个子类,包含构造方法和用户自定义方法。这些方法的目的如下所述。
方法:
构造方法
构造方法由 __init__() 定义。假设用户选择了第二个菜单的第三个选项(“确认付款”)。在这种情况下,将调用 “customer” 类的构造函数,以在创建 “customer” 类的对象时初始化客户信息并完成购买任务。此方法将接受四个参数:姓名、地址、电话和现金。
购买信息():
该方法已被定义为显示包含订单号、订单日期、客户姓名、客户地址、客户电话、购买产品列表和所有购买产品总价的购买详情。在这里,订单号将使用random()函数生成。如果用户添加的现金值大于或等于cart_amount变量的值,则将调用该方法。
下面提供了客户类的脚本:
'''
'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.")创建对象
在定义了应用程序的必要类之后,添加脚本以创建对象以使用类变量,并调用方法以完成“蛋糕店应用程序”的实现。首先,将定义“shop”类的对象,并通过使用这个对象调用display_menu()方法来显示主菜单。在脚本中,使用了第一个无限循环以在应用程序开始时和在确认或取消购买后显示主菜单。当用户选择主菜单的第三个选项(“退出”)时,这个循环将被终止,应用程序将关闭。第二个无限循环用于将产品添加到购物车中,直到用户输入“none”,并在添加或移除产品到购物车后显示第二个菜单。 如果用户选择第二个菜单的第三个(“确认支付”)或第四个(“取消”)选项,则此循环将被终止。假设用户选择了第二个菜单的第三个选项,并且用户添加的现金金额少于cart_amount值。那么第二个菜单将再次出现,并显示消息:“您的余额不足。”。在终止第二个无限循环后,cart_items和cart_amount的值将被清除,以便进行下一次购买。以下是该部分的脚本:
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()应用输出
在将所有脚本顺序添加到shop.py文件后,您可以检查应用程序是否正常工作。如何使用这个应用程序在本教程的这一部分中已显示。
运行应用程序
首先,用户必须打开终端并前往存放products.txt和shop.py文件的地点。您必须将这些文件存储在同一位置以正确获取输出。运行以下命令以执行应用程序:
python3 shop.py执行前一个命令后将出现以下输出。这是该应用程序的主菜单。用户可以通过输入“1”或“2”或“3”选择输出中显示的三个选项中的任何一个。如果用户输入“1”,将显示产品列表。如果用户输入“2”,将出现输入提示以输入产品名称。如果用户输入“3”,应用程序将关闭。如果用户输入任何其他字符,菜单将再次出现。
显示产品
如果用户输入“1 ”,将会出现以下输出。products.txt 文件的内容已在此输出中显示。用户可以选择输出中显示的任何蛋糕名称以添加到购物车中,并且用户必须选择菜单的第二个选项来执行此任务。
通过主菜单将产品添加到购物车
在应用中有两种方式可以将产品添加到购物车。第一种方式是选择主菜单上的第二个选项。如果用户输入“2 ”,将出现以下输出。用户必须输入文件中存在的任何蛋糕项目的名称,以将其添加到购物车。
如果用户输入存在于产品列表中的“泥蛋糕”,将出现以下输出。输出显示该产品已添加到购物车,用户可以通过再次输入产品名称来添加另一个产品。如果用户不想添加任何产品,则必须输入“无”。
如果添加另一个名为“咖啡蛋糕”的产品,将出现以下输出:
如果输入值为“无”,则会出现以下输出。购物车商品列表显示在输出中。已经添加了两个蛋糕项目:“泥蛋糕”和“咖啡蛋糕”。“泥蛋糕”的价格为¥35,“咖啡蛋糕”的价格为¥22。蛋糕的总价为¥35 + ¥22=¥57,显示在输出中。第二个菜单在展示购物车信息后显示。用户可以通过此菜单添加产品、移除产品、购买已添加到购物车的产品,以及取消购买。
通过使用第二个菜单将产品添加到购物车
如果用户输入了“2 ”,将出现以下输出。用户需要输入文件中存在的任何蛋糕名称,以将其添加到购物车中。
在输入值中键入“香草蛋糕”后,将出现以下输出。用户可以通过再次输入产品名称来添加更多商品到购物车。如果用户不想再添加更多产品,则必须输入“无”以停止将产品添加到购物车。
在输入值为none后,将显示以下输出。输出显示新的产品香草蛋糕已被添加到购物车中,并且香草蛋糕的价格已与购物车金额相加。因此,总金额现在为$57 + $30=$87。第二个菜单再次出现。此菜单的目的之前已解释过。
将产品从购物车中移除
如果用户输入2作为输入值,则会出现以下输出。用户必须输入购物车中存在的任何蛋糕项目的名称,以将其从购物车中移除。如果用户输入的任何值在购物车中不存在,则会打印错误信息。
如果用户输入存在于 products.txt 文件中但不在购物车中的 “巧克力蛋糕” 作为输入值,以下输出将会出现。因此,错误信息“购物车中不存在该产品。”已出现在输出中,并且购物车中没有添加或移除任何物品。购物车的总金额也没有变化。
如果用户输入了存在于购物车中的值“咖啡蛋糕”,则会出现以下输出。成功消息“产品已从购物车中移除”已打印。输出还显示“咖啡蛋糕”已从购物车中移除,并且该商品的价格已从购物车金额中扣除。“咖啡蛋糕”的价格为$22。因此,购物车的总金额现在为$87 - $22=$65。
如果购物车中的所有商品都被移除,将出现以下输出。输出显示了两个消息。一个是提示移除最后一件商品,另一个是告知用户购物车现在是空的。由于购物车中没有商品,第二个菜单已消失,主菜单再次出现。
支付
第二个菜单的第三个选项用于通过添加客户的信息和购物车金额来确认购买。如果用户在将一些蛋糕项目添加到购物车后输入“3 ”以选择第二个菜单的第三个选项,将出现以下输出。输出显示有两个蛋糕项目已添加到购物车,蛋糕的总价格为$60。在输入值“3 ”后,将出现提示输入客户姓名。接下来,还会出现其他输入提示,以添加与客户相关的其他信息和购买产品的现金金额。
在以下输出中,客户的姓名、地址、电话号码和现金金额已被添加。但添加的现金金额少于产品的总价格。购物车的总金额为60美元,而添加的现金金额为45美元。因为这个原因,出现了消息:“您的余额不足。” 订单被取消,购物车变为空。主菜单再次出现。
如果用户添加的现金等于或超过购物车的总金额,以下输出将会出现。这里,购物车的总价格为35美元,而用户增加了100美元作为现金值,大于总价格。输出还显示生成了一个随机数作为订单号,当前系统日期被打印为订单日期。主菜单再次出现以便进行下一次购买。用户的当前余额为100美元 - 35美元=65美元。如果同一用户再次从商店购买任何蛋糕商品,则购买金额将从用户的当前余额中扣除。
如果用户再次购买且购买金额少于他们当前的余额,将出现以下输出。根据输出,两个蛋糕项目已被添加到购物车,蛋糕的总价格为47美元。用户添加了0美元现金,但客户当前的余额为65美元。因此,支付已成功完成,并且“谢谢”消息已被打印。用户的当前余额为65美元 - 47美元=18美元。
如果同一用户再次将商品添加到购物车,并且该商品的总价格低于用户当前的余额,则会出现以下输出。用户在最后一笔交易后的当前余额为18美元,但商品的总价格为30美元。因此,消息“您余额不足。”已经打印出来,订单被取消,购物车变为空。
如果用户将 $12 与 $18 添加在一起购买价值 $30 的 "香草蛋糕",则会出现以下输出。在购买后,用户的当前余额为 $0。
取消支付
用户可以在将商品添加到购物车后,通过选择第二个菜单的第四个选项或从购物车中移除所有商品来取消订单。如果用户通过键入“4 ”选择第二个菜单的第四个选项,将会出现以下输出。消息“您已取消购买。”已被打印以取消订单。从购物车中移除所有商品来取消订单的方法之前已显示。在取消订单后,将出现主菜单。
关闭应用程序
通过选择主菜单上的第三个选项,可以关闭应用程序。如果用户输入“3 ”以关闭应用程序,将出现以下输出。应用程序已通过消息“来自应用程序的终止”终止。
本应用的局限性
本教程展示了如何通过Python类实现一个非常简单的基于文本的应用程序。但是,这个应用程序有一些限制,如下所述:
- 没有订单或客户信息被永久存储。该应用程序需要保留先前销售的记录。可以创建两个文本文件来存储订单和客户信息。
- 在此应用程序中没有维护库存记录,这是商店应用的重要组成部分。如果任何产品缺货,则应向用户传递一条消息。
- 如果用户多次添加相同的产品,则每个产品将被单独添加,这样效率很低。如果同一产品被多次添加,则必须统计购物车中每种产品的数量。
- 没有单一命令可以在不取消订单的情况下将购物车中的所有物品删除。用户必须逐个删除每个物品才能清空购物车。
- 完成订单支付后,剩余客户余额不会显示。这将帮助用户为下一个订单添加现金。
***本教程的读者将尝试实现上述功能,以提高他们的编程技能,并使应用程序在学习中更加高效。
关于此主题的视频教程
结论
本教程为初学者提供了实现简单文本基于Python应用程序的指南。商店应用程序的基本功能在本教程中得以实现,例如产品列表、添加到购物车、从购物车中移除、支付系统和取消付款。为了简单起见,我们在这里使用文本文件永久存储数据。但是,任何标准的数据库应用程序,如SQLite和MySQL,都可以更有效地管理应用程序数据。





















