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

查看:165
本文介绍了是否可以在 Python 中预先声明一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Python 中预先声明一个函数?我想在声明之前使用我自己的 cmp 函数对列表进行排序.

Is it possible to forward-declare a function in Python? I want to sort a list using my own cmp function before it is declared.

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

我已经组织了我的代码以在调用之后放置 cmp_configs 方法的定义.它因此错误而失败:

I've organized my code to put the definition of cmp_configs method after the invocation. It fails with this error:

NameError: name 'cmp_configs' is not defined

有没有办法在使用之前声明"cmp_configs 方法?它会让我的代码看起来更干净吗?

Is there any way to "declare" cmp_configs method before it's used? 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.

考虑在 Python 中需要向前声明函数的情况:

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

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

其中 end_conditionend_result 之前已定义.

Where end_condition and end_result have been previously defined.

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

Is the only solution to reorganize the code and always put definitions before invocations?

推荐答案

如果你不想在使用之前定义一个函数,而在之后定义它是不可能,在其他模块中定义怎么样?

If you don't want to define a function before it's used, and defining it afterwards is impossible, what about defining it in some other module?

从技术上讲,您仍然首先定义它,但它很干净.

Technically you still define it first, but it's clean.

您可以创建如下递归:

def foo():
    bar()

def bar():
    foo()

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

Python's functions are anonymous just like values are anonymous, yet they can be bound to a name.

在上面的代码中,foo() 并没有调用名称为 foo 的函数,而是调用一个刚好绑定到名称 foo 的函数.点呼叫.可以在其他地方重新定义 foo,然后 bar 将调用新函数.

In the above code, foo() does not call a function with the name foo, it calls a function that happens to be bound to the name foo at the point the call is made. It is possible to redefine foo somewhere else, and bar would then call the new function.

您的问题无法解决,因为这就像要求获取尚未声明的变量.

Your problem cannot be solved because it's like asking to get a variable which has not been declared.

这篇关于是否可以在 Python 中预先声明一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆