2013-04-05 125 views
-1

我想知道是否有办法自动定义一个函数。比如我要像一组功能:有没有办法在python中自动定义一个函数?

def add1: 
    list.append(x) 
def add2: 
    list.append(y) 
def add3: 
    list2.append(x) 
... 

的问题是,我必须定义大量的这些,232是准确的。有没有更快的方法来做到这一点?另外,我使用Python 3.2。

+1

什么是你想定义不同的行为做?你可以使用lambda函数,如果它正在模式中做某件事。 – karthikr 2013-04-05 14:37:03

+4

更好的问题是,为什么你认为你需要232函数几乎相同 – jozefg 2013-04-05 14:37:11

+5

为什么你想定义232函数?这听起来像[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 – 2013-04-05 14:37:24

回答

1

您可以使用exec

例如:

def your_common_function(i, txt): 
    # here you may decide what to do with arguments according to "i" value 
    if i == 1: 
     print(txt) 
    else: 
     print(txt+'s') 

for i in range(1, 233): 
    exec("def add%d(txt):\n\tyour_common_function(%d, txt)" % (i, i)) 

add1("hello world") # prints "hello world" 
add167("hello world") # prints "hello worlds" 

编辑我改变了我的代码,以便您可以按“功能编号”

+0

谢谢。那可行。 – Anthony 2013-04-05 16:09:38

相关问题