以下是一个示例代码,演示了如何实现包含其他产品的产品捆绑销售:
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
class Bundle:
def __init__(self, name, *products):
self.name = name
self.products = list(products)
def add_product(self, product):
self.products.append(product)
def remove_product(self, product):
self.products.remove(product)
def calculate_total_price(self):
total_price = 0
for product in self.products:
total_price += product.price
return total_price
# 创建产品
product1 = Product("Product 1", 10)
product2 = Product("Product 2", 20)
product3 = Product("Product 3", 30)
# 创建捆绑销售产品
bundle = Bundle("Bundle", product1, product2)
# 添加/移除产品
bundle.add_product(product3)
bundle.remove_product(product1)
# 计算总价格
total_price = bundle.calculate_total_price()
print("Total price of bundle:", total_price)
在上面的代码中,我们定义了一个Product
类表示产品,具有名称和价格属性。然后,我们定义了一个Bundle
类表示捆绑销售的产品,包含名称和一个产品列表。该类提供了添加和移除产品的方法,并提供了计算捆绑销售产品总价格的方法。
在示例中,我们创建了三个产品对象,并将两个产品添加到一个捆绑销售产品中。然后,我们从捆绑销售产品中移除一个产品,并计算捆绑销售产品的总价格。
输出结果为:Total price of bundle: 50
,表示捆绑销售产品的总价格为50。
下一篇:包含其他分支信息的主分支