python - 为什么我需要在 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))
解决方案
您的.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
推荐阅读
- string - Perl:从文件读取后如何检查数组列中单词的最大宽度?
- android - 如何在移动开发者播放器(flutter/ios/android/reactnative)中播放 Prime 或 Netflix 视频?
- node.js - 在 reactjs 中进行服务器端调试
- html - 如何使用css反转动画?
- mysql - Mysql 连接应该从表 A 中返回所有不在表 B 中的 AND 表 B 的 where 子句
- typescript - 如何在 vue.js 中绑定类?
- python - 超过最大重试次数
- google-sheets - 匿名共享 Google 表格
- android-studio - 解决错误“app:mergeDebugResources”和“文件名必须以 XML 结尾”
- nginx - Kubernetes Ingress Nginx 服务:AWS API Gateway/CloudFront 返回 403