@decorate
def target():
print("running target()")
def target():
print("running target()")
target = decorate(target)
def decorate(func):
def inner():
print("running inner()")
return inner
>>> target()
running inner()
>>> target
<function decorate.<locals>.inner at 0x04899D18>
registry = []
def register(func):
# 装饰器函数也可以不定义内部函数
print("running register(%s)" % func)
registry.append(func)
return func
@register
def f1():
print("running f1()")
@register
def f2():
print("running f2()")
def f3():
print("running f3()")
def main():
print("running main()")
print("registry ->", registry)
f1()
f2()
f3()
if __name__ == "__main__":
main()
@register作用到f1和f2上,在导入时,在main()调用前就执行了。
f3没有装饰器,就没有在main()调用前执行@register。
在main()调用后,明确调用f1()、f2()、f3()才执行函数。
>>> import registration
running register(<function f1 at 0x0189A730>)
running register(<function f2 at 0x0189A6E8>)
promos = []
def promotion(promo_func):
promos.append(promo_func)
return promo_func
@promotion
def fidelity(order):
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
@promotion
def bulk_item(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
@promotion
def large_order(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
def best_promo(order):
"""Select best discount available
"""
return max(promo(order) for promo in promos)
新的促销策略,用@promotion装饰器即可添加。
促销策略函数不用以_promo结尾,可以任意命令。
促销策略可以在任意模块定义,只需要使用@promotion装饰器即可。
参考资料: 《流畅的Python》
联系客服