是否有可能在Python中前向声明一个函数?我想在声明之前使用我自己的cmp函数对列表进行排序。

print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)])

我把cmp_configs方法的定义放在调用之后。它会失败,报错如下:

NameError: name 'cmp_configs' is not defined

是否有任何方法在使用cmp_configs方法之前“声明”它?

有时候,很难重新组织代码来避免这个问题。例如,在实现某些形式的递归时:

def spam():
    if end_condition():
        return end_result()
    else:
        return eggs()

def eggs():
    if end_condition():
        return end_result()
    else:
        return spam()

其中end_condition和end_result已经在前面定义。

唯一的解决方案是重新组织代码并始终在调用之前放置定义吗?


当前回答

将调用包装到它自己的函数中,以便

foo()

def foo():
    print "Hi!"

会破碎,但

def bar():
    foo()

def foo():
    print "Hi!"

bar()

将正常工作。

Python中的一般规则是,函数应该在使用之前定义,这并不一定意味着它需要在代码中处于更高的位置。

其他回答

如果对cmp_configs的调用在它自己的函数定义中,那么应该没有问题。我举个例子。

def a():
  b()  # b() hasn't been defined yet, but that's fine because at this point, we're not
       # actually calling it. We're just defining what should happen when a() is called.

a()  # This call fails, because b() hasn't been defined yet, 
     # and thus trying to run a() fails.

def b():
  print "hi"

a()  # This call succeeds because everything has been defined.

一般来说,把你的代码放在函数中(比如main())会解决你的问题;只需在文件末尾调用main()即可。

如果您不想在使用函数之前定义它,并且在使用之后定义它是不可能的,那么在其他模块中定义它呢?

从技术上讲,您仍然先定义它,但它是干净的。

你可以创建一个像下面这样的递归:

def foo():
    bar()

def bar():
    foo()

Python的函数是匿名的,就像值是匿名的一样,但是它们可以绑定到一个名称。

在上面的代码中,foo()并不调用foo名称的函数,它调用的函数恰好在调用时绑定到foo名称。可以在其他地方重新定义foo,然后bar将调用新函数。

您的问题无法解决,因为这就像要求获得一个未声明的变量。

在Python中不能前向声明函数。如果在定义函数之前已经执行了逻辑,那么无论如何都可能遇到问题。将你的动作放在脚本末尾的if __name__ == '__main__'中(通过执行一个你命名为“main”的函数,如果它不是平凡的),你的代码将更加模块化,如果你需要,你将能够将它作为一个模块使用。

同样,用生成器表达式替换该列表理解(即,打印"\n".join(str(bla) for bla in sorted(mylist, cmp=cmp_configs)))

另外,不要使用已弃用的cmp。使用键并提供小于函数。

将调用包装到它自己的函数中,以便

foo()

def foo():
    print "Hi!"

会破碎,但

def bar():
    foo()

def foo():
    print "Hi!"

bar()

将正常工作。

Python中的一般规则是,函数应该在使用之前定义,这并不一定意味着它需要在代码中处于更高的位置。

一种方法是创建处理程序函数。尽早定义处理程序,并将处理程序放在需要调用的所有方法的下面。

然后,当您调用处理程序方法来调用函数时,它们将始终可用。

处理程序可以接受一个名为ofmethodtocall的参数。然后使用一堆if语句来调用正确的方法。

这将解决你的问题。

def foo():
    print("foo")
    #take input
    nextAction=input('What would you like to do next?:')
    return nextAction

def bar():
    print("bar")
    nextAction=input('What would you like to do next?:')
    return nextAction

def handler(action):
    if(action=="foo"):
        nextAction = foo()
    elif(action=="bar"):
        nextAction = bar()
    else:
        print("You entered invalid input, defaulting to bar")
        nextAction = "bar"
    return nextAction

nextAction=input('What would you like to do next?:')

while 1:
    nextAction = handler(nextAction)