[英]Python flow of execution
有人能解釋一下python程序的執行流程,尤其是關於main函數的流程嗎? 如果將其與C的執行進行比較和對比將會有所幫助。
當你執行“python myprog.py”時,python interpeter將逐行開始運行腳本:
import os #import the os module
print "prints somthing"
def f(num): ... # define a function
a = 5 / 2.0 # calculating stuff stuff ...
if __name__ == '__main__': #__name__ is '__main__' only if this was the file that was started by the interpeter
f(a) #calling the function f...
在C中,有一個特殊的功能“main”將在啟動時執行。 這個(如上所述對於python不適用)
沒有深入,在c中你有一個特定的“入口”功能(主要):
int main() {
// stuff
}
編譯此函數,可執行文件將以它開頭。
在python中,您通常會加載一個特定的模塊(類似於python mymodule.py
)並通過檢查__name__
的值來驗證main-ness:
if "__main__" == __name__:
print "this is main"
__name__
變量通常是模塊的名稱( "mymodule.py"
),當它是你加載的主模塊時會有例外(然后它會自動設置為"__main__"
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.