python - 使用 python 字典和 Lambda 函数
问题描述
这是我编写带有选项的简单二维码生成器的代码。How do I run the send function only when the correct option is chosen? 除非在分配时调用它,否则我不会调用发送函数?如果是这样,我怎样才能让字典包含我需要但不调用它的值?
// imports
import sys
import os
import requests
from PIL import Image
from io import BytesIO
// api-endpoint
URL = "https://api.qrserver.com/v1/create-qr-code"
data = "Example Text"
size = "200x200"
color = "0-0-0" # black
bgcolor = "255-255-255" # white
# defining a params dict for the parameters to be sent to the API
PARAMS = {'data': data, 'size': size, 'color': color, 'bgcolor': bgcolor}
check = False
while(not check):
print("Welcome to my QR code generator")
print("--------------------------------")
print("Press 1 to add data (Default: \"Example Text\"")
print("Press 2 to change size (Default: 200x200)")
print("press 3 to change color (Default: 0-0-0 <-- Black)")
print("Press 4 to change background color (Default: 255-255-255 <-- White)")
print("Press 5 to show your selected options")
print("Press c to create QR code")
print("Press q to exit")
def Send(x):
# sending get request and saving the response as response object
r = requests.get(url=URL, params=x)
r.content
i = Image.open(BytesIO(r.content))
i.show()
def CleanupAndQuit():
exit()
menuchoices = {'1': AddData, '2': ChangeSize, '3': ChangeColor,
'4': ChangeBGColor, '5': ShowAll, 'c': Send(PARAMS), 'q': CleanupAndQuit}
ret = menuchoices[input()]()
if ret is None:
print("Please enter a choice")
解决方案
In the definition of menuchoices
you are immediately calling the function Send
with PARAMS
.
What you might try instead is using lambda expression:
menuchoices = {
'c': lambda: Send(PARAMS)
}
This way you avoid immediate call to Send
and keep it configured for lazy evaluation.
推荐阅读
- python - 使用 FLD 中的最高特征值为 2D 数据投影多个集群
- r - 使用 r 中的配置文件将每周值分解为每日值
- javascript - 如何在提交时验证表单?
- reactjs - 初始化前无法访问“authReducer”
- php - preg_match - 忽略可选括号
- python - 过滤 Numpy 的数组数组
- office-js - office-addin 未从 nodejs spdy 服务器加载,从本地 nodejs 运行正常,快速服务器
- angular - 如何在 Angular10/Typescript 中刷新页面时运行函数
- angular - Ngxs或行为主体,选择哪个
- javascript - 用于验证重复斜杠的正则表达式