是否有可能在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已经在前面定义。
唯一的解决方案是重新组织代码并始终在调用之前放置定义吗?
如果对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()即可。
如果对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()即可。