python类class例子-超市商品购物车及结算的例子,如下文。
class Product:
def __init__(self,name,price,num):
self.name=name#商品名称
self.price=price#单价
self.num = num#购买数量
class Shoppingcart:
def __init__(self):
self.items = []
def add_item(self, item):
self.items.append(item)
def calculate_total(self):
for e in self.items:
print(e.name,e.price,e.num)
total = sum([e.price*e.num for e in self.items])
return total
cart = Shoppingcart()
cart.add_item(Product("白菜", 2,3.0))
cart.add_item(Product("萝卜", 1.5,2))
cart.add_item(Product("猪肉", 3.0,12))
total_price = cart.calculate_total()
print("应付总金额:",total_price)
运行输出如下内容:
白菜, 2,3.0
萝卜, 1.5,2
猪肉, 3.0,12
应付总金额:45.0