0

The idea is that when a new function is written, it's variable name is appended to a list automatically.

Just to note, I realise I can just use mylist.append(whatever) but I'm specifically looking for a way to automatically append, rather than manually.

So, if we start with...

def function1(*args):
    print "string"

def function2(*args):
    print "string 2"

mylist = []

...is there a way to append 'function1' and 'function2' to mylist automatically so that it would end up like this...

mylist = [function1, function2]

Specifically, I'd like to have the variable name listed, not a string (e.g. "function1").

I'm learning Python and just experimenting, so this doesn't serve any particular purpose at the moment, I just want to know if it's possible.

Thanks in advance for any suggestions and happy answer any questions if I've not been clear.

**

4

2 回答 2

1

只需将函数对象添加到列表中:

mylist = [function1, function2]

或使用.append()

mylist.append(function1)
mylist.append(function2)

Python 函数是一流的对象。它们是值,就像类、字符串和整数一样。

如果您想为整个模块自动执行此操作,您可以使用该globals()函数快速列出迄今为止在模块中定义的所有函数,并借助inspect.isfunction()谓词的一些帮助:

import inspect
mylist = [v for v globals().itervalues() if inspect.isfunction(v) and v.__module__ == __name__]

测试确保我们只列出当前模块中的v.__module__ == __name__函数,而不是我们导入的任何内容。

但是,显式仍然比隐式好。在每个函数下方添加mylist.append(functionname),或使用装饰器:

mylist = []
def listed(func):
    mylist.append(func)
    return func

@listed
def function1():
    pass

@listed
def function2():
    pass

您使用装饰器“标记”的每个功能@listed都会添加到mylist列表中。

于 2013-05-11T17:26:13.580 回答
0

原则上,您可以使用装饰器来做到这一点,这可能符合半自动解决方案:

@gather
def function1():
    print "function 1"

@gather
def function2():
    print "function 2"

这种装饰器的一种实现本质上是一个将函数作为参数的函数:

function_list = []

def gather(func):
    function_list.append(func)  # or .append(func.__name__)
    return func

在这个简单的化身中,它可能根本没有用,但流行的库和框架通常采用这种技术的某种增强版本。例如,请参阅 Flask 的@app.route装饰器以指定处理特定 HTTP 请求的函数。

于 2013-05-11T17:39:57.003 回答