简体   繁体   English

Python function 执行顺序

[英]Python function execution order

I couldn't find any question related to this subject.我找不到与此主题相关的任何问题。 But does python execute a function after the previous called function is finished or is there in any way parallel execution?但是 python 在前面调用的 function 完成之后是否执行 function 或者是否有任何并行执行?

For example:例如:

def a():
    print('a')

def b():
    print('b')

a()
b()

So in this example I would like to know if I can always be sure that function b is called after function a is finished, even if function a is a very long script?所以在这个例子中我想知道我是否总是可以确定在function a完成调用function b ,即使function a是一个很长的脚本? And what is the defenition of this, so I can look up documentation regarding this matter.这是什么意思,所以我可以查找有关此问题的文档。

Thanks谢谢

Defining the function doesn't mean its execution.定义函数并不意味着它的执行。 Since you defined a first, the function object for a will be created first, so as for there calls.由于您首先定义a a ,因此将首先创建a的函数对象,以便调用。

You can take it as execution timeline starting from top to bottom.您可以将其作为从上到下开始的执行时间线。

TLDR: b will only ever run after a is exited. TLDR: b只会在a退出后运行。

Each Python thread will only ever execute one thing at a time and respect ordering of expressions and statements.每个 Python 线程一次只会执行一件事,并尊重表达式和语句的顺序。 For the most part, this means executing "top-to-bottom", though function definitions, control flow and other elements can affect execution order.在大多数情况下,这意味着执行“自上而下”,尽管函数定义、控制流和其他元素会影响执行顺序。 Ordering is preserved in any case, however.然而,在任何情况下都保留排序。


Strictly speaking, the Python language only defines the execution order of expressions .严格来说,Python 语言只定义了表达式执行顺序

Python evaluates expressions from left to right. Python 从左到右计算表达式。 Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.请注意,在评估赋值时,右侧先于左侧进行评估。

Neither simple statements nor compound statements define an evaluation order.简单语句复合语句都没有定义求值顺序。

However, Python is defined based on a byte code interpreting virtual machine , and the reference implementation is based on a stackbased bytecode evaluation loop .但是,Python 是基于字节码解释虚拟机定义的,而参考实现是基于基于堆栈的字节码评估循环 All major implementations of Python preserve the observable behaviour of executing one statement after the other. Python 的所有主要实现都保留了一个接一个执行语句的可观察行为。

There is no parallel execution of functions in python. python中没有并行执行函数。 The above functions will be executed in the same sequence that they were called in regardless of the amount of computation workload of either of the functions.无论任何一个函数的计算工作量如何,上述函数都将按照调用它们的相同顺序执行。

In python functions are by default executed in the order they appear.在 python 中,函数默认按照它们出现的顺序执行。 However if you call them in a different order they will execute as such.但是,如果您以不同的顺序调用它们,它们将按原样执行。 So in your example所以在你的例子中

def a():
    print('a')
def b():
    print('b')

b()
a()

then b() will execute before a()然后b()将在a()之前执行

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

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