简体   繁体   English

python 中的 function 实际如何工作?

[英]How function in python actually works?

I got a question for how a function actually works.我有一个关于 function 实际工作原理的问题。 From my understanding, the function can be call only if the call() is below the function which seems something like this:据我了解,只有当 call() 低于 function 时才能调用 function ,看起来像这样:

def main():
     num1 = int(input("Please enter first number: "))
     print_num(num1)
main()

But I don't get it why the main() in print_num function can call the def main(), which locate under it.但我不明白为什么 print_num function 中的 main() 可以调用位于它下面的 def main()。

def print_num(num1):
     print(num1)
     main()

def main():
     num1 = int(input("Please enter first number: "))
     print_num(num1)
main()

When you run your python code, only the function definition is read and the function name stored.当您运行 python 代码时,仅读取 function 定义并存储 function 名称。 The code inside the function is not evaluated until it has been called. function 中的代码在被调用之前不会被评估。 So for example, the below when run will define the func1 and func2 then when it calls func1 only then the code of func1 is evaluated.因此,例如,下面的 when run 将定义 func1 和 func2 然后当它调用 func1 时,才评估 func1 的代码。 At this point the code has already seen the func2 definition so its aware of it and there is no issue.此时代码已经看到了 func2 定义,因此它知道它并且没有问题。

def func1():
    func2()


def func2():
    print("hello world")

func1()

OUTPUT OUTPUT

hello world

However if we put the call to func1 before func2但是,如果我们在 func2 之前调用 func1

def func1():
    func2()

func1()

def func2():
    print("hello world")

In this case func1 is called before the code has even seen func2.在这种情况下,func1 在代码甚至还没有看到 func2 之前就被调用了。 So when it evaluates the code in func1 its no idea what func2 is and we get an error.因此,当它评估 func1 中的代码时,它不知道 func2 是什么,我们得到一个错误。

Traceback (most recent call last):
  File "C:/Users/cdoyle5/PycharmProjects/stackoverflow/chris.py", line 4, in <module>
    func1()
  File "C:/Users/cdoyle5/PycharmProjects/stackoverflow/chris.py", line 2, in func1
    func2()
NameError: name 'func2' is not defined
def print_num(num1):
     print(num1)
     main()

def main():
     num1 = int(input("Please enter first number: "))
     print_num(num1)
main()

The above code is executed in the following order:上述代码按以下顺序执行:

(1)def print_num(num1):
(6)     print(num1)
(7)     main()
(2)def main():
(4)     num1 = int(input("Please enter first number: "))
(5)     print_num(num1)
(3)main()

It's about the order in which it has been executed.这是关于它的执行顺序。 So even if you write所以即使你写

def print_num(num1)

on line 1, it's body will be the 6th line of code to be executed, that is, only after it has been called.在第 1 行,它的主体将是要执行的第 6 行代码,也就是说,只有在它被调用之后。 Python will only execute the body of a function after it has been called. Python 只会在调用 function 后执行它的主体。

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

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