首页 > 解决方案 > 为什么我需要在 get 函数后使用这个括号?

问题描述

我在理解这段代码时遇到了问题:

def dispatch_dict(operator, x, y):
    return {
        'add': lambda: x + y,
        'sub': lambda: x - y,
        'mul': lambda: x * y,
        'div': lambda: x / y,
    }.get(operator, lambda: None)() # here I don't understand this brackets  
                                    #  after closing get function

print(dispatch_dict('sub', 2, 4))

标签: python

解决方案


您的.get(operator, lambda: None)返回函数对象 - 阅读例如https://medium.com/python-pandemonium/function-as-objects-in-python-d5215e6d1b0d,然后添加 () 调用该函数。

也许这种简化会有所帮助:

def add_lambda(x, y):
    add = lambda: x + y  # Note this is not PEP-8 compliant
    return add

the_function = add_lambda(31, 11)  # returns lambda function
the_function()  # here are your brackets, this returns 42

推荐阅读