【问题标题】:Definining a function from a list从列表中定义函数
【发布时间】:2017-06-13 12:12:18
【问题描述】:

假设我有一个字符串列表:obj = ['One','Two','Three'],我怎么能把这个列表中的每个值变成一个函数,它们都执行非常相似的函数?例如:

def one():
    print("one")

def two():
    print("two")

def three():
    print("three")

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

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()

【问题讨论】:

标签: python list function


【解决方案1】:

使用闭包:

>>> 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

也许dict 会更方便:

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

【讨论】:

  • 这可行,但假设我想将每个功能用于按钮,我将如何删除括号以便能够使用command=
  • @Ernxst 我不确定您的意思是“删除括号”,这只是我演示调用这些函数。但是函数是 Python 中的一等对象。它们在列表中。例如,要访问某个函数,请使用function[1] 获取列表中的第二个函数。
  • 我知道我可以为该功能的列表建立索引,但我想创建几个具有不同功能的按钮,所以我不能真正使用列表索引来设置它们的command
  • @Ernxst 这对我来说似乎很简单...循环列表,根据需要附加函数:command=function[i] 或其他。如果需要,您也可以将它们放入字典中。
  • 没关系,我只是没有注意它
【解决方案2】:

如果您也想管理名称,使用 exec 的简单解决方案:

L=['one','two','three']
prog='def xxx():print("xxx")'
for name in L:
    exec(prog.replace('xxx',name))

定义了三个函数。

>>>two()
two
>>>

【讨论】:

    猜你喜欢
    • 2013-11-26
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2019-12-07
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    相关资源
    最近更新 更多