if __name__=='__main__'在Python代碼中常見,一直不是很明白這個的用法,最近在學習測試開發剛好提到這點,就把這個知識點記錄下來吧。
個人理解如下:每個.py文件的__name__都的等於__main__,當且僅當__nam__爲__main__的時候才執行if語句的代碼。也就是說,只有在當前.py執行的時候纔會運行if語句的代碼,如果是B.py是被當前A.py文件調用的,則被調用的B.py文件的if語句的代碼是不會被調用的,因爲被調用的B.py的__name__在此時是爲B,而不是__main__,A.py的__name__才爲__main__。
舉例1:
test01.py源碼如下:
class TestModule:
def test_01(self):
print("這是01方法!")
def test_02(self):
print("這是02方法!")
print(__name__)
test02.py源碼如下:
from test01 import TestModule
if __name__=='__main__':
tm1 = TestModule()
在運行test02.py的時候,輸出test01.py的__name__
舉例2:
test01.py源代碼如下:
class TestModule:
def test_01(self):
print("這是01方法!")
def test_02(self):
print("這是02方法!")
if __name__=='__main__':
tm = TestModule()
tm.test_01()
tm.test_02()
test02.py源代碼如下:
from test01 import TestModule
if __name__=='__main__':
tm1 = TestModule()
tm1.test_01()
tm1.test_02()
運行test02.py,只有test02.py的tm1.test_01()和tm1.test_02()被運行了。