locals gloabls global
global 定义全局变量
下面两个是内置函数:
locals() 以字典形式访问局部变量
globals() 以字典形式访问全局变量,注意 不能访问局部变量
示例:
通过内省模块globals() 全局变量,找出以_promotion结尾的所有函数,一遍被其他模块调用
def fidelity_promotion(order): """积分为1000或以上, 5%折扣""" discount = 0 if order.customer.fidelity >= 1000: discount = order.total() * 0.05 return discount def bulk_promotion(order): """单个商品数量为20个或以上, 10%折扣""" discount = 0 for item in order.cart: if item.quantity >= 20: discount += item.total() * 0.01 return discount def large_order_promotion(order): """订单中不同的商品达到10个或以上, 7%折扣""" discount = 0 distinct_items = {item.product for item in order.cart} if len(distinct_items) >= 10: discount = order.total() * 0.07 return discount promos = [globals()[name] for name in globals() if name.endswith("_promotion")] for item in promos: print(item)
>>>
<function large_order_promotion at 0x00562ED0>
<function fidelity_promotion at 0x00562300>
<function bulk_promotion at 0x00562F18>