首页 > 解决方案 > 使用 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")

标签: python

解决方案


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.


推荐阅读