是否可以在 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 中的一般规则是函数应该在使用之前定义,这不一定意味着它需要在代码中更高。
关于python - 如何前向声明一个函数以避免后面定义的函数出现 `NameError` s?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1590608/