从列表中定义函数

Ern*_*xst 7 python function list

假设我有一个字符串列表:obj = ['One','Two','Three'],我怎样才能将此列表中的每个值转换为一个函数,它们都执行非常相似的函数?例如:

def one():
    print("one")

def two():
    print("two")

def three():
    print("three")
Run Code Online (Sandbox Code Playgroud)

现在我知道你可以预先定义函数并使用字典(如下所示),但是说我想要创建很多函数,这需要很多代码才能这样做,因此我想知道是否有我可以用更短的方式来解决这个问题.

import tkinter as tk

def one():
    print("one")

def two():
    print("two")

def three():
    print("three")

obj = ['One','Two','Three']
func = {'One': one, 'Two': two, 'Three': three}

def create_btn():
    btns =  {}
    for i in obj:
        text = i
    for col in range(1):
        for row in range(len(obj)):
            btns[row, col] = tk.Button(canvas, text=str(text),
                                       command=func[i]).grid(column=col,
                                                                 row=row)
            btns[row, col] = canvas.create_window(50, row,
                                                  window = btns[row, col])
            canvas.pack()


root = tk.Tk()          
root.geometry = ("750x600")

btn_frame = tk.Frame(root)
canvas = tk.Canvas(root)

create_btn()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

jua*_*aga 8

使用闭包:

>>> def print_me(string):
...     def inner():
...         print(string)
...     return inner
...
>>> functions = [print_me(s) for s in obj]
>>> functions[0]()
One
>>> functions[1]()
Two
>>> functions[2]()
Three
Run Code Online (Sandbox Code Playgroud)

也许一个dict会更方便:

>>> functions = {s:print_me(s) for s in obj}
>>> functions['One']
<function print_me.<locals>.wrapper at 0x102078bf8>
>>> functions['One']()
One
>>>
Run Code Online (Sandbox Code Playgroud)