简体   繁体   English

从函数列表返回函数的python函数

[英]python function that returns a function from list of functions

I want to make following function: 我要执行以下功能:

 1)input is a number. 
 2)functions are indexed, return a function whose index matches given number

here's what I came up with: 这是我想出的:

def foo_selector(whatfoo):
    def foo1():
        return
    def foo2():
        return
    def foo3():
        return
    ...

    def foo999():
        return

    #something like return foo[whatfoo]

the problem is, how can I index the functions (foo#)? 问题是,如何索引函数(foo#)? I can see functions foo1 to foo999 by dir(). 我可以通过dir()看到函数foo1到foo999。 however, dir() returns name of such functions, not the functions themselves. 但是,dir()返回此类函数的名称,而不是函数本身。 In the example, those foo-functions aren't doing anything. 在示例中,这些foo函数没有执行任何操作。 However in my program they perform different tasks and I can't automatically generate them. 但是,在我的程序中,它们执行不同的任务,因此我无法自动生成它们。 I write them myself, and have to return them by their name. 我自己写它们,必须按他们的名字归还它们。

Use a decorator to accumulate a list of functions. 使用装饰器累积功能列表。

func_list = []

def listed_func(func):
    func_list.append(func)
    return func

@listed_func
def foo1():
   pass

@listed_func
def foo2():
   pass

Now you can easily access the functions by index in a list. 现在,您可以通过列表中的索引轻松访问功能。

You could also create a dictionary if you want to access the functions by name: 如果要按名称访问函数,也可以创建字典:

func_dict = {}

def collected_func(func):
    func_dict[func.__name__] = func
    return func

Or extract the index from the name, and use that as the dict key (since dicts are not ordered, you'll want to sort the keys if you want to iterate over them in some order): 或从名称中提取索引,并将其用作dict键(由于dict不排序,因此,如果要按某种顺序遍历它们,则需要对键进行排序):

func_dict = {}

def collected_func(func):
    key = int("".join(c for c in func.__name__ if c.isdigit()))
    func_dict[key] = func
    return func

Or explicitly pass the index number to the decorator: 或者显式地将索引号传递给装饰器:

func_dict = {}

def collected_func(key):
    def decorator(func):
        func_dict[key] = func
        return func
    return decorator

@collected_func(12)
def foo():
    pass

You could simply place all of your functions into an array, something like: 您可以将所有函数简单地放入一个数组中,例如:

def foo_selector(whatfoo):
    def foo1():
        return
    def foo2():
        return
    def foo3():
        return
    ...

    def foo999():
        return

    foo_list = [
        foo1,
        foo2,
        ...
        foo999
    ]

    return foo_list[whatfoo]

Here are a couple other ways you could do it: 您可以通过以下几种方法来做到这一点:

eval("foo{}()".format(whatfoo))

or 要么

locals()['foo{}'.format(whatfoo)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM