简体   繁体   English

如果python“一行一行”运行文件,它如何在定义之前使用函数?

[英]If python run the file "line after line" how can it use a function before it's been defined?

I am learning python at the moment, after learning Java, now I know that java first compiles the whole file and then run it, in python from what I understand it run the program while it compiles it "line by line".我现在正在学习python,在学习了Java之后,现在我知道java首先编译整个文件然后运行它,从我理解的python中它运行程序,同时它“逐行”编译它。

So what I don't understand is how can I call a function before I define it.所以我不明白的是如何在定义函数之前调用它。 I am used from Java to write all my "helping methods" after the method that need them, I think it's easier to read that way.我在 Java 中习惯于在需要它们的方法之后编写我所有的“帮助方法”,我认为这样更容易阅读。 So I tried to do the same thing in python, and it worked.所以我尝试在 python 中做同样的事情,它奏效了。 Why?为什么?

An important designation here is that it is not the order in which the functions are created that matters, it matters when the call to the function is done .这里的一个重要说明是,创建函数顺序并不重要,重要的是何时调用函数

Take for example the following code:以下面的代码为例:

def add_one(new):
    return my_add(new, 1)

def my_add(x, y):
    return x + y

my_var = 2
print("The value of my_var is: {}".format(my_var))
my_var = add_one(my_var)
print("The value of my_var is: {}".format(my_var))

It yields它产生

The value of my_var is: 2 my_var 的值为:2

The value of my_var is: 3 my_var 的值为:3

This is happening because by the time the add_one function is called, both functions already exist.发生这种情况是因为在调用add_one函数时,这两个函数都已经存在。 But if try and call add_one before defining my_add ...但是,如果尝试和呼叫add_one之前定义my_add ...

def add_one(new):
    return my_add(new, 1)

my_var = 2
print("The value of my_var is: {}".format(my_var))
my_var = add_one(my_var)
print("The value of my_var is: {}".format(my_var))

def my_add(x, y):
    return x + y

We get:我们得到:

The value of my_var is: 2
Traceback (most recent call last):
  File "c:\Users\wundermahn\Desktop\Stack.py", line 6, in <module>
    my_var = add_one(my_var)
  File "c:\Users\J39304\Desktop\Stack.py", line 2, in add_one
    return my_add(new, 1)
NameError: name 'my_add' is not defined

See Does the order of functions in a Python script matter?请参阅Python 脚本中的函数顺序是否重要? for more更多

You can't call a function before it is defined.您不能在定义之前调用函数。 This program will throw an exception:这个程序会抛出一个异常:

foo()

def foo():
    print("Hello from foo")

If this isn't what you meant, please update your question to be more specific.如果这不是您的意思,请更新您的问题以使其更具体。

The short answer is: you can't简短的回答是:你不能

Most longer python programs include a statement like this:大多数较长的python程序都包含这样的语句:

if __name__ == "__main__":
    # do something which is usually call a 'main()' function

at the very end of their main script which means that contents of the if statement is only executed if this file is the one executed, as opposed to being imported.在他们的主脚本的最后,这意味着 if 语句的内容只有当这个文件被执行时才会执行,而不是被导入。

All the functions must be defined prior to being called, and by the time it hits that if statement at the bottom of the file, they've all been defined.所有的函数都必须在被调用之前定义,当它到达文件底部的 if 语句时,它们都已经定义好了。

To add to the other answers, I just want to mention that while the code execution at runtime is sequential, when the interpreter hits a function definition, only the definition line gets executed.为了补充其他答案,我只想提一下,虽然运行时的代码执行是顺序的,但当解释器遇到函数定义时,只会执行定义行。 Here is to citing the documentation :这是引用文档

The function definition does not execute the function body;函数定义不执行函数体; this gets executed only when the function is called. this 仅在调用函数时执行。 ... ...

This also leads to the noteworthy behavior of mutable types as default parameter values.这也导致可变类型作为默认参数值的值得注意的行为。 It's good to know about this, as things can turn out pretty surprising otherwise:很高兴知道这一点,否则事情会变得非常令人惊讶:

Default parameter values are evaluated from left to right when the function definition is executed.执行函数定义时从左到右计算默认参数值。 This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call.这意味着表达式会在定义函数时计算一次,并且每次调用都使用相同的“预计算”值。 This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (eg by appending an item to a list), the default value is in effect modified.这对于理解何时默认参数是可变对象(例如列表或字典)尤其重要:如果函数修改了对象(例如,通过将项目附加到列表),则默认值实际上被修改了。 This is generally not what was intended.这通常不是预期的。 A way around this is to use None as the default, and explicitly test for it in the body of the function, eg:解决这个问题的一种方法是使用None作为默认值,并在函数体中明确测试它,例如:

def whats_on_the_telly(penguin=None):
    if penguin is None:  # this conditional ensures the expected behavior
        penguin = []
    penguin.append("property of the zoo")
    return penguin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM