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 Jupyter Notebooks in Azure There’s a new feature in Azure, and I stumbled on it when someone posted a link on Twitter. Apologies, I can’t remember who, but I did click on the A...
python装饰器的使用 1. 装饰者模式 装饰者模式是常用的软件设计模式之一。通过此设计模式,我们能够在不修改任何底层代码情况下,给已有对象赋予新的职责。python中可以用装饰器简单地实现装饰者模式。 1.1 将函数作为参数传递 在 C/C++ 中,函数指针可以将函数作为参数传递给另一...
简历有错别字被拒绝聘用?文档被领导说?Python实现永无错别字!... 找出中文错别字 1.5 代码获取 你可以通过下面命令将代码下载到实验楼环境中,作为参照对比进行学习。 $ wget http://labfile.oss.aliyuncs.com/courses/828/Document.tar 可以预想到,假设我们的语料库...
Seaborn 和 Matplotlib 数据可视化 【本文还未正式完成,仍在更新中。。。】 简述 Python 中,数据可视化一般是通过较底层的 Matplotlib 库和较高层的 Seaborn 库实现的,本文主要介绍一些常用的图的绘制方法。在正式开始之前需要导入以下包 import numpy as np # 线性代数库 impo...
一键将 Python2 代码自动转化为 Python3 问题 Python2 的代码直接在 Python3 环境运行的话会报错误: 如果大量的代码,无论是批量替换,还是逐行修改都够累的,这活儿表示不能干! 有没有办法一键转换呢? 百度了一下发现网上的方法如下: 可以利用 Python 内置工具 2to3.py,...