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>

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-26
  • 2021-09-29
  • 2021-11-02
  • 2022-01-20
猜你喜欢
  • 2021-07-03
  • 2022-12-23
  • 2021-09-23
  • 2022-12-23
  • 2022-02-14
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案