综合编程

Defining a function from a list

微信扫一扫,分享到朋友圈

Defining a function from a list
0

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!

每刻报销签下全球领先物联网独角兽企业「鲁尔物联」

上一篇

Spring mvc &commat;requestmapping best practices

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
Defining a function from a list

长按储存图像,分享给朋友