Python advanced (6)-use a first-class function to implement the design mode and python Design Mode

Source: Internet
Author: User

Python advanced (6)-use a first-class function to implement the design mode and python Design Mode
Main content of this article

Classic "policy" Mode

 

Python advanced-directory

The code in this article is on github: https://github.com/ampeeg/cnblogs/tree/master/pythonadvanced

 

Classic "policy" Mode
'''Classic policy mode: encapsulates a series of algorithms that can be replaced by each other, so that the algorithms can change independently and the customers who use them. Assume that a clothing store in contemporary mall has three discount rules: 1. for Members, 8.5 off for all products. 2. Buy two or more items for the same product, except for the first item, the remaining 7.5 off 3, buy 5 different products, all goods off three rules can only enjoy one. '''From abc import ABC, abstractmethodfrom collections import namedtupleCustomer = namedtuple ('customer', 'name vip ') # consumer object class Clothing: # clothing def _ init _ (self, name, quantity, price): self. name = name self. quantity = quantity self. price = price def total (self): return self. price * self. quantityclass Order: # Order class def _ init _ (self, customer, clothing, promotion = None): self. customer = customer self. clothing = list (clothing) self. promotion = promotion def total (self): if not hasattr (self, '_ total'): self. _ total = sum (item. total () for item in self. clothing) 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 () class Promotion (ABC): # create three discount base classes @ abstractmethod def discount (self, order ):''': returns calculates the discount ''' class VipPromo (Promotion): # member discount ": returns member 8.5 off" def discount (self, order): return order. total ()*. 15 if order. customer. vip else 0 class TwoPromo (Promotion): # Second ''': returns more than two pieces of clothing, second and later ''' def discount (self, order): discount = 0 for item in order. clothing: if item. quantity> = 2: discount + = (item. total ()-item. price )*. 25 return discountclass FivePromo (Promotion): # more than 5 "": returns buy more than 5 different kinds of clothing, off per piece "" def discount (self, order ): distinct_items = {item. name for item in order. clothing} if len (distinct_items)> = 5: return order. total ()*. 2 return 0if _ name _ = "_ main _": # create a consumer, joe = Customer ('John Doe ', 0) # non-member ann = Customer ('ann Smith ', 1) # member # create a shopping cart clothing = [Clothing ('pants', 6,200), Clothing ('skirt', 1,150 ), clothing ('shoes', 2,230)] print (Order (joe, clothing, VipPromo () # <Order total: 1810.00 due: 1810.00> not a member, print (Order (ann, clothing, VipPromo () # <Order total: 1810.00 due: 1538.50> Members, print (Order (joe, clothing, twoPromo () # <Order total: 1810.00 due: 1502.50> print (Order (joe, clothing, FivePromo () for more than two pieces (Order () # <Order total: 7.5 due: 1810.00> No discounts for no more than 5 types of clothing. extend ([Clothing ('shirt', 1, 90), Clothing ('br', 2,130)]) print (Order (joe, clothing, FivePromo ())) # <Order total: 2160.00 due: 1728.00> off for 5 types
'''Use the function below to complete the "classic" policy ''' from abc import ABC, abstractmethodfrom collections import namedtupleCustomer = namedtuple ('customer', 'name vip ') # consumer object class Clothing: # Clothing class def _ init _ (self, name, quantity, price): self. name = name self. quantity = quantity self. price = price def total (self): return self. price * self. quantityclass Order: # Order class def _ init _ (self, customer, clothing, promotion = None): self. customer = customer self. clothing = list (clothing) self. promotion = promotion def total (self): if not hasattr (self, '_ total'): self. _ total = sum (item. total () for item in self. clothing) return self. _ total def due (self): if self. promotion is None: discount = 0 else: discount = self. promotion (self) return self. total ()-discount def _ repr _ (self): fmt = '<Order total :{:. 2f} due :{:. 2f}> 'Return fmt. format (self. total (), self. due () def VipPromo (order): # member discount return order. total ()*. 15 if order. customer. vip else 0def TwoPromo (order): # The second discount = 0 for item in order. clothing: if item. quantity> = 2: discount + = (item. total ()-item. price )*. 25 return discountdef FivePromo (order): # distinct_items = {item. name for item in order. clothing} if len (distinct_items)> = 5: return order. total ()*. 2 return 0if _ name _ = "_ main _": # create a consumer, joe = Customer ('John Doe ', 0) # non-member ann = Customer ('ann Smith ', 1) # member # create a shopping cart clothing = [Clothing ('pants', 6,200), Clothing ('skirt', 1,150 ), clothing ('shoes', 2,230)] print (Order (joe, clothing, VipPromo) # <Order total: 1810.00 due: 1810.00> print (Order (ann, clothing, VipPromo) # <Order total: 1810.00 due: 1538.50> Members, print 1810.00 off (Order (joe, clothing, TwoPromo) # <Order total: due: 1502.50> print (Order (joe, clothing, FivePromo) for two or more pieces of data) # <Order total: 7.5 due: 1810.00> no discount for clothing in five cases. extend ([Clothing ('shirt', 1, 90), Clothing ('br', 2,130)]) print (Order (joe, clothing, FivePromo) # <Order total: 2160.00 due: 1728.00> off for 5 types
Promos = [VipPromo, TwoPromo, FivePromo] def best_stratety (order): return max (promo (order) for promo in promos) print (Order (joe, clothing, best_stratety )) # <Order total: 2160.00 due: 1728.00> automatically selects the optimal policy
''' Use the globals function to find the current global number. The returned dictionary format is '''promos = [globals () [name] for name in globals () if name. endswith ("Promo")] print (promos) # finds three policy functions [<function FivePromo at 0x10c363b70>, <function TwoPromo at 0x10c363ae8>, <function VipPromo at 0x10abd3048>] def best_stratety (order): return max (promo (order) for promo in promos) print (Order (ann, clothing, best_stratety )) # <Order total: 2160.00 due: 1728.00>
'''We can create a class, manage all commands, and rewrite its instance to an callable object '''class MacroCommand: def _ init _ (self, commands ): self. commands = list (commands) def _ call _ (self): for command in self. commands: command ()

 

Python advanced articles

Python advanced-directory

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.