第6章一等関数を使って設計モードを実現する
11659 ワード
# 《 Python》
# 6
# , 。
# 6.1 : “ ”
# , ,“ ” 。
# “ ” , 《 : 》 “ ” 。
# , 6.1.2 , 。
# 6.1.1 “ ”
# 6-1 Order ,
from abc import ABC,abstractmethod
from collections import namedtuple
Customer=namedtuple('Customer','name fidelity')
class LineItem:
def __init__(self,product,quantity,price):
self.product=product
self.quantity=quantity
self.price=price
def total(self):
return self.price*self.quantity
class Order:
def __init__(self,customer,cart,promotion=None):
self.customer=customer
self.cart=list(cart)
self.promotion=promotion
def total(self):
if not hasattr(self,'__total'):
self.__total=sum(item.total() for item in self.cart)
return self.__total
def due(self):
if self.promotion is None:
discount=0
else:
discount=self.promotion.discount(self)
return self.total()-discount
def __repr__(self):
fmt=' '
return fmt.format(self.total(),self.due())
class Promotion(ABC):
@abstractmethod
def discount(self,order):
"""" ( )"""
class FidelityPromo(Promotion):
""" 1000 5% """
def discount(self,order):
return order.total()*.05 if order.customer.fidelity>=1000 else 0
class BulkItemPromo(Promotion):
""" 20 10% """
def discount(self,order):
discount=0
for item in order.cart:
if item.quantity>=20:
discount += item.total()* .1
return discount
class LargeOrderPromo(Promotion):
"""" 10 7% """
def discount(self,order):
distinct_items={item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total()* .07
return 0
# 6-2 Order
joe=Customer('John Doe',0) #joe 0
ann=Customer('Ann Smith',1100) #ann 1100。
cart=[ LineItem('banana',4,.5), # 。
LineItem('apple',10,1.5),
LineItem('watermellon',5,5.0) ]
print(Order(joe,cart,FidelityPromo())) #fidelityPromo joe 。
#
print(Order(ann,cart,FidelityPromo())) #ann 5% , 1000。
#
banana_cart=[ LineItem('banana',30,.5), #banana_cart 30 10 。
LineItem('apple',10,1.5) ]
print(Order(joe,banana_cart,BulkItemPromo())) #BulkItemPromo joe 1.50 。
#
long_order=[ LineItem(str(item_code),1,1.0) #long_order 10 , 1.00 。
for item_code in range(10) ]
print(Order(joe,long_order,LargeOrderPromo())) #LargerOrderPromo joe 7% 。
#
print(Order(joe,cart,LargeOrderPromo()))
#
# 6.1.2 “ ”
# 6-3 Order
# 6-4 Order
# 6.1.3 :
# 6-5 best_promo ,
# 6-6 best_promo ,
# 6.1.4
# 6-7 , promos
# 6-8 promotions , promos
# 6.2 “ ”
# 6-9 MacroCommand
# 6.3
# 6.4
転載先:https://www.cnblogs.com/larken/p/9557324.html