在 Python 中的文件末尾声明函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3754240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:34:51  来源:igfitidea点击:

Declare function at end of file in Python

pythonfunctionformatting

提问by TheGentleOne

Is it possible to call a function without first fully defining it? When attempting this I get the error: "function_nameis not defined". I am coming from a C++ background so this issue stumps me.

是否可以在没有完全定义的情况下调用函数?尝试此操作时,我收到错误消息:“未定义function_name”。我来自 C++ 背景,所以这个问题难倒了我。

Declaring the function before works:

在工作前声明函数:

def Kerma():
        return "energy / mass"    

print Kerma()

However, attempting to call the function without first defining it gives trouble:

但是,尝试在未先定义的情况下调用该函数会带来麻烦:

print Kerma()

def Kerma():
    return "energy / mass"

In C++, you can declare a function after the call once you place its header before it.

在 C++ 中,一旦将函数头放在函数前面,就可以在调用之后声明函数。

Am I missing something here?

我在这里错过了什么吗?

采纳答案by Muhammad Alkarouri

One way that is sort of idiomatic in Python is writing:

Python 中一种惯用的方式是编写:

def main():
    print Kerma()

def Kerma():
    return "energy / mass"    

if __name__ == '__main__':
    main()

This allows you to write you code in the order you like as long as you keep calling the function mainat the end.

这允许您按照您喜欢的顺序编写代码,只要您main在最后继续调用该函数。

回答by Eli Bendersky

This isn't possible in Python, but quite frankly you will soon find you don't need it at all. The Pythonic way to write code is to divide your program into modules that define classes and functions, and a single "main module" that imports all the others and runs.

这在 Python 中是不可能的,但坦率地说,您很快就会发现根本不需要它。编写代码的 Pythonic 方式是将您的程序划分为定义类和函数的模块,以及一个导入所有其他模块并运行的“主模块”。

For simple throw-away scripts get used to placing the "executable portion" at the end, or better yet, learn to use an interactive Python shell.

对于简单的一次性脚本,习惯于将“可执行部分”放在最后,或者更好的是,学习使用交互式 Python shell。

回答by eumiro

Python is a dynamic languuage and the interpreter always takes the state of the variables (functions,...) as they are at the moment of calling them. You could even redefine the functions in some if-blocks and call them each time differently. That's why you have to define them before calling them.

Python 是一种动态语言,解释器总是采用变量(函数,...)在调用它们时的状态。您甚至可以在某些 if 块中重新定义函数,并每次以不同的方式调用它们。这就是为什么你必须在调用它们之前定义它们。

回答by martineau

When a Python module (.py file) is run, the top level statements in it are executed in the order they appear, from top to bottom (beginning to end). This means you can't reference something until you've defined it. For example the following will generate the error shown:

当 Python 模块(.py 文件)运行时,其中的顶级语句按照它们出现的顺序执行,从上到下(从开始到结束)。这意味着在定义某些内容之前您无法引用它。例如,以下将生成显示的错误:

c = a + b  # -> NameError: name 'a' is not defined
a = 13
b = 17

Unlike with many other languages, defand classstatements are executable in Python—not just declarative—so you can't reference either aor buntil that happens and they're defined. This is why your first example has trouble—you're referencing the Kerma()function before its defstatement has executed and body have been processed and the resulting function object bound to the function's name, so it's not defined at that point in the script.

不像许多其他语言,def以及class语句是可执行的Python中,不只是声明,所以你不能可以引用ab在此之前,他们正在定义。这就是您的第一个示例出现问题的原因——您Kerma()def执行其语句和处理主体之前引用该函数,并且生成的函数对象绑定到该函数的名称,因此它没有在脚本中的那个点定义。

Programs in languages like C++ are usually preprocessed before being run and during this compilation stage the entire program and any #includefiles it refers to are read and processed all at once. Unlike Python, this language features declarative statements which allow the name and calling sequence of functions (or static type of variables) to be declared (but not defined), before use so that when the compiler encounters their name it has enough information to check their usage, which primarily entails type checking and type conversions, none of which requires their actual contents or code bodies to have been defined yet.

使用 C++ 等语言编写的程序通常在运行之前进行预处理,在此编译阶段,整个程序及其#include引用的任何文件都会被一次性读取和处理。与 Python 不同的是,这种语言具有声明性语句,允许在使用之前声明(但未定义)函数(或静态类型的变量)的名称和调用序列,以便编译器在遇到它们的名称时有足够的信息来检查它们用法,主要涉及类型检查和类型转换,其中任何一个都不需要定义它们的实际内容或代码体。