《流畅的python》读书笔记(四)
6.1 策略模式
将不同对的策略封装到不同的策略方法中, 创建策略实例,传入上下文(实际场景), 执行计算方法获得策略的结果集, 执行排序方法选出最佳策略.
from operator import itemgetter
class Promotion():
"""策略"""
def __init__(self, price, quantity):
self.price = price
self.quantity = quantity
self.comparison()
def A(self):
discount = 10
return "A", discount
def B(self):
discount = self.price*self.quantity*0.1
return "B", discount
def comparison(self):
self.decision, self.max_discount = sorted(
[self.A(), self.B()], key=itemgetter(1), reverse=True)[0]
p = Promotion(20, 10)
print(p.decision, p.max_discount)
如果使用函数定义策略用globals()可以获取所有策略的函数名映射,通过globals()"func_name"调用策略.
6.2 命令模式
把操作封装成函数作为命令
在客户端中的命令菜单中调用命令,执行操作
import random
def command_A():
print("do A")
def command_B():
print("do B")
menu = ["command_A", "command_B"]
client_command = random.choice(menu)
result = globals()[client_command]()
7.4 变量的作用域
python在编译函数体的时候会判断变量是本地还是全局, 如果有本地变量,则不会读取全局变量, 但是如果变量在本地的的定义是在调用之后会报错.
a = b = 1
def test():
print(a)
print(b)
b = 2
test()
7.8 内置装饰器
缓存装饰器
@lru_cache
把耗时的函数结果自动缓存起来, 传入相同参数的时候直接调用,
用于优化递归算法,或者web后台的视图函数, 函数的所有参数必须可散列.
7.9 单分派泛函数装饰器
@functools.singledispatch
区分处理不同的数据类型,实现调用同一个函数,不同的处理逻辑,
相当于在函数内部进行if–elif–else判断参数类型做不同的处理
import functools
@functools.singledispatch
def func(s):
"""处理对象类型数据的基函数"""
print("str is", s)
@func.register(int)
def _(num):
"""处理int类型的扩展函数"""
print("int is", num)
func(2)
7.10 参数化装饰器
接收不同的参数,完成不同功能的装饰器
def factory(flag=True):
"""定义装饰器的函数"""
def wrapper(func):
"""内层函数"""
if flag:
print("before func")
func()
if not flag:
print("after func")
return func
return wrapper
@factory(False)
def function():
"""被装饰函数"""
print("here is func")
print("----------------------------")
function()