程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python medium pair__ name__ == __main__ understand

編輯:Python
 stay Python We often see that when running a program, there will always be if __name__ == "__main__"
This code . We know , stay Java There will be one main Method , When we run the program , Just run one
individual main The method can , stay python It's the same with China ,,“if __name__==’__main__:” Like
A sign , Symbolize Java And other languages , Tell the programmer , The code entry is here .
Let's show you through the code :
# modular 01
from demo_02 import *
a = 50
print(" Little ")
print(a)
# 02 modular
b = 100
print(" This is the module 02")
print(b)

Running results :

  But sometimes ,02 Part of the code of the module doesn't want to run directly 01 Module runs directly , The following changes are made :


# modular 01
from demo_02 import *
a = 50
print(" Little ")
print(a)
# 02 modular
b = 100
print(" This is the module 02")
if __name__ =="__main__" :
print(b)

Now let's have a look , Running results :

  We found no input 100, Description is running 01 When the module ,print(b) This code does not run .

Let's continue with the demonstration :

from demo_02 import *
# modular 01
a = 50
print(" Little ")
print(a)
print(' modular A in __name__ Value :{}'.format(__name__))
# 02 modular
b = 100
print(" This is the module 02")
print(b)
print(' modular 02 in __name__ Value :{}'.format(__name__))

When we run 02 When the module :

  And when we run 01 When the module :

  comparison , function 02 when __name__ The value is :__main__; function 01 when ,02 Module __name__ The value is :__demo_02, So I found : When which module is executed directly , The module “__name__” The value is “__main__”, The first mock exam is imported into another module. ,“__name__” The value of is the real name of the module .

therefore , When running “if __name__=='__main__':” When the sentence is , If the current module is directly executed ,__name__ The value is __main__, The result of conditional judgment is True,“if __name__=='__main__':” The following code block will be executed .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved