我創建了兩個類。在類購物車中,我需要實作計算總價和折扣的方法 get_total_price。折扣取決于計數產品:
count discount
at least 5 5%
at least 7 10%
at least 10 20%
at least 20 30%
more than 20 50%
class Product:
def __init__(self, name, price, count):
self.name = name
self.price = price
self.count = count
class Cart:
def __init__(self, *products_list):
self.products_list = products_list
def get_total_price(self):
pass
products = (Product('p1',10,4),
Product('p2',100,5),
Product('p3',200,6),
Product('p4',300,7),
Product('p5',400,9),
Product('p6',500,10),
Product('p7',1000,20))
cart = Cart(products)
print(cart.get_total_price())
The result of running the program should be 24785.0
有人可以幫忙,因為我不知道如何獲取屬性(價格,計數)來計算折扣。
uj5u.com熱心網友回復:
似乎 cart.products_list 回傳一個包含產品串列的元組(因此,另一個元組中的一個元組)。如果不是有意的,請洗掉“*”。
這是當前結構的作業解決方案;如果洗掉“*”,請洗掉 get_total_price 方法中的 [0]。
def discount_mult(q):
if q > 20:
return .5
elif q >= 20:
return .7
elif q >= 10:
return .8
elif q >= 7:
return .9
elif q >= 5:
return .95
else:
return 1
class Product:
def __init__(self, name, price, count):
self.name = name
self.price = price
self.count = count
class Cart:
def __init__(self, *products_list):
self.products_list = products_list
def get_total_price(self):
return sum([i.price*i.count*discount_mult(i.count) for i in self.products_list[0]])
products = (Product('p1',10,4),Product('p2',100,5),Product('p3',200,6),Product('p4',300,7),
Product('p5',400,9),Product('p6',500,10),Product('p7',1000,20))
cart = Cart(products)
print(cart.get_total_price())
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/520200.html
標籤:Python哎呀
上一篇:生成器模式build()方法輸出
