簡體   English   中英

理解python中的執行流程

[英]understanding the execution flow in python

剛接觸python,對執行流程感到困惑:

為了詳細說明,我正在說明以下示例:

示例 1:

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

def python():
    print("testing main")

if __name__ == "__main__":
    hello()

**output :**
    hello world
    testing main

注意:我知道__name__ == "__main__"的用法

示例 2:

python()

def python():
    print("testing main")

**output**
File "main_flow.py", line 2, in <module>
python()
NameError: name 'python' is not defined

據我所知,python 以順序方式執行程序(如果我錯了,請糾正我),因此在示例 2 中,它在遇到方法 python() 時無法找到它。

我的困惑是為什么在示例 1 中沒有發生類似的錯誤,這種情況下的執行流程是什么。

編輯 1 :當您在 python 中調用自定義函數時,它必須知道它在文件中的位置。 我們使用def function_name():來定義我們在腳本中使用的函數的位置。 我們必須調用def function_name():我們調用之前function_name()否則該腳本將不知道function_name()並會引發異常(找不到函數的錯誤)。

通過運行def function_name():它只讓腳本知道有一個名為function_name()但在你調用它之前它實際上並沒有運行function_name()的代碼。

在您的第二個示例中,您在腳本到達def python() python()之前調用python() ,因此它還不知道python()是什么。

示例 1 的順序是:

1.    def hello(): # Python now knows about function hello()
5.        print("hello world")
6.        python()

2.    def python(): # Python now knows about function python()
7.        print("testing main")

3.    if __name__ == "__main__":
4.       hello() 

示例 2 的順序是:

1.    python()    # Error because Python doesn't know what function python() is yet

-     def python(): # Python doesn't reach this line because of the above error
-         print("testing main")

示例 2 的解決方案是:

1.     def python(): # Python now knows about function python()
3.         print("testing main")

2.     python()   

編輯 2:從腳本的角度重申示例 1

def hello(): 
def python(): 
if __name__ == "__main__":
hello() 
print("hello world")
python()
print("testing main")

這是腳本將看到和運行每行代碼的順序。 很明顯,腳本知道python()因為 def 在第 2 行調用, python()在第 6 行調用。

當涉及到定義時,您似乎不明白范圍的含義。 閱讀它。 函數的作用域在 def 期間不執行,它只在函數被調用時執行。

不是__name__ == '__main__' ,而是因為被定義的函數執行之前在第二個例子中的函數調用。

您的第一個示例定義所有函數執行函數python 因為hello在函數定義之后調用(因此沒有名稱錯誤)!

如果將hello()放在定義之間,則會再次出現錯誤:

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

hello()

def python():
    print("testing main")

給出:

hello world 
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-21db1c6bfff8> in <module>()
      3     python()
      4 
----> 5 hello()
      6 
      7 def python():

<ipython-input-7-21db1c6bfff8> in hello()
      1 def hello():
      2     print("hello world")
----> 3     python()
      4 
      5 hello()

NameError: name 'python' is not defined

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM