是否可以在 Python 中预先声明一个函数? - Is it possible to forward-declare a function in Python?

10/14 04:34
阅读数 0

问题:

Is it possible to forward-declare a function in Python?是否可以在 Python 中预先声明一个函数? I want to sort a list using my own cmp function before it is declared.我想在声明之前使用我自己的cmp函数对列表进行排序。

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

I've organized my code to put the definition of cmp_configs method after the invocation.我已经组织了我的代码以在调用之后放置cmp_configs方法的定义。 It fails with this error:它失败并出现此错误:

NameError: name 'cmp_configs' is not defined

Is there any way to "declare" cmp_configs method before it's used?有没有办法在使用之前“声明” cmp_configs方法? It would make my code look cleaner?它会让我的代码看起来更干净吗?

I assume that some people will be tempted to tell me that I should just reorganize my code so that I don't have this problem.我想有些人会很想告诉我,我应该重新组织我的代码,这样我就不会有这个问题了。 However, there are cases when this is probably unavoidable, for instance when implementing some forms of recursion.但是,在某些情况下这可能是不可避免的,例如在实现某些形式的递归时。 If you don't like this example, assume that I have a case in which it's really necessary to forward declare a function.如果你不喜欢这个例子,假设我有一个案例,其中确实有必要转发声明一个函数。

Consider this case where forward-declaring a function would be necessary in Python:考虑在 Python 中需要预先声明函数的这种情况:

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

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

Where end_condition and end_result have been previously defined.其中end_conditionend_result先前已定义。

Is the only solution to reorganize the code and always put definitions before invocations?是重新组织代码并始终在调用之前放置定义的唯一解决方案吗?


解决方案:

参考一: https://en.stackoom.com/question/6fmy
参考二: https://stackoom.com/question/6fmy
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部