Fluent Python Ch06

( 출처 : 전문가를 위한 파이썬 / Fluent Python )


[ Design Patterns with First-Class Functions ]

1. Classic Strategy

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


Context

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 = '<Order total: {:.2f} due: {:.2f}>'
	    return fmt.format(self.total(), self.due())


Strategy

< abstract base class >

  • abstarctmethod discount는 반드시 구현해야!
class Promotion(ABC):
    @abstractmethod
	def discount(self, order):
		"""Return discount as a positive dollar amount"""


Strategy # 1

class FidelityPromo(Promotion): 
    
    """5% discount for customers with 1000 or more fidelity points"""
    
	def discount(self, order):
		return order.total() * .05 if order.customer.fidelity >= 1000 else 0


Strategy # 2

class BulkItemPromo(Promotion):
    
	"""10% discount for each LineItem with 20 or more units"""
    
	def discount(self, order):
        discount = 0
        for item in order.cart:
	        if item.quantity >= 20:
    		    discount += item.total() * .1
        return discount


Strategy # 3

class LargeOrderPromo(Promotion):
    
	"""7% discount for orders with 10 or more distinct items"""
    
	def discount(self, order):
        distinct_items = {item.product for item in order.cart}
        if len(distinct_items) >= 10:
	        return order.total() * .07
        return 0


joe = Customer('John Doe', 0)
ann = Customer('Ann Smith', 1100)

cart1 = [LineItem('banana', 4, .5),LineItem('apple', 10, 1.5), LineItem('watermellon', 5, 5.0)]
cart2 = [LineItem('banana', 30, .5),LineItem('apple', 10, 1.5)]
cart3 = [LineItem(str(item_code), 1, 1.0) for item_code in range(10)]
Order(joe, cart1, FidelityPromo())
# <Order total: 42.00 due: 42.00>

Order(ann, cart1, FidelityPromo())
# <Order total: 42.00 due: 39.90>

#-----------------------------------------------------------#

Order(joe, cart2, BulkItemPromo())
# <Order total: 30.00 due: 28.50>

#-----------------------------------------------------------#

Order(joe, cart3, LargeOrderPromo())
# <Order total: 10.00 due: 9.30>

Order(joe, cart1, LargeOrderPromo())
# <Order total: 42.00 due: 42.00>


2. Function-Oriented Strategy

굳이 다 class로 구현하지 말고, function으로!

class Order: 
    # 중략 #
    
    def due(self):
    	if self.promotion is None:
		    discount = 0
	    else:
    		#discount = self.promotion.discount(self) ( 기존 )
            discount = self.promotion(self) # ( 수정 )
	    return self.total() - discount
    
	# 중략 #
def fidelity_promo(order):
	"""5% discount for customers with 1000 or more fidelity points"""
	return order.total() * .05 if order.customer.fidelity >= 1000 else 0

def bulk_item_promo(order):
	"""10% discount for each LineItem with 20 or more units"""
	discount = 0
    for item in order.cart:
	    if item.quantity >= 20:
    		discount += item.total() * .1
    return discount

def large_order_promo(order):
	"""7% discount for orders with 10 or more distinct items"""
	distinct_items = {item.product for item in order.cart}
	if len(distinct_items) >= 10:
		return order.total() * .07
	return 0


# Order(joe, cart1, FidelityPromo()) (기존)
Order(joe, cart1, fidelity_promo (수정)

Tags:

Categories:

Updated: