是否有可能在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已经在前面定义。
唯一的解决方案是重新组织代码并始终在调用之前放置定义吗?
一种方法是创建处理程序函数。尽早定义处理程序,并将处理程序放在需要调用的所有方法的下面。
然后,当您调用处理程序方法来调用函数时,它们将始终可用。
处理程序可以接受一个名为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)
如果对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()即可。