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之random库 random库是使用随机数的一个python标准库。 random()是不能直接访问的,需要导入 random 模块,然后通过 random 静态对象调用该方法。即使用前需要导入:import random random库包含两类函...
Functional Options Posted on November 7, 2018 A while ago I read about functional options pattern in Go and then immediately forgot abou...
RHEL 6.6下Python 2.6.6升级到Python 3.6.6 最近一段时间shell脚本写得很溜,很有成就感,一想到被自己落下的Python就感到十分心虚。开始坚持学习Python!先将自己的测试机器的Python升级到Python 3.6.6。简单整理、记录一下! ...
Top 10 Reasons Why You Should Learn Python Top 10 Reasons To Learn Python Programming languages have been around for ages, and every decade sees the launch ...
ROS探索总结(五十二)—— MoveIt!中的运动学插件... MoveIt!是ROS中一个重要的集成化开发平台,由一系列移动操作的功能包组成,提供运动规划、操作控制、3D感知、运动学等功能模块,是ROS社区中使用度排名前三的功能包,目前已经支持众多机器人硬件平台。 MoveIt!中...