Defining a function from a list

综合编程 2018-06-25

Say I have a list of strings: obj = ['One','Two','Three']
, how would I be able to turn each value in this list into a function where they all carry out very similar functions? For example:

def one():
    print("one")

def two():
    print("two")

def three():
    print("three")

Now I know you can define the functions beforehand and use a dictionary (as shown below), but say I wanted many functions to be created, it would take a lot of code to do so and therefore I would like to find out if there is a shorter way I can go about this.

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

Use a closure:

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

Maybe a dict
would be more convenient:

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

责编内容by:Hello, buddy! (源链)。感谢您的支持!

您可能感兴趣的

Python 使用 ElementTree 模块来处理 XML 最近使用 Python 来发送 SOAP 请求以测试 Web Service 的性能,由于 SOAP 是基于 XML 的,故免不了需要使用 Pyth...
Python机器学习算法入门之梯度下降法实现线性回归... 1. 背景 文章的背景取自 An Introduction to Gradient Descent and Linear Regression ,本文想在...
造轮子寻找UAF漏洞 前言 轮子的核心是使用 Frida 来实现的。 菜鸡的心得,大神骂的时候温柔点,谢谢^_^ 由于本人没有做过漏洞...
Python简介之输入和输出 输出 输入 输出 用print()在括号中加上字符串就可以向屏幕上输出指定的文字。比如输出‘hello,world!’,用...
十最受欢迎的机器学习和数据科学Python库... 2018年将会是人工智能和机器学习快速发展的一年,有专家表示:相较之下Python比Java更加接地气,也自然而然地成为机器学习的首选语言 ...