一、背景
經(jīng)常在python程序中會使用這條語句,但是卻習(xí)以為常,并沒有真正理解其含義,那它具體的含義,有什么作用呢?其實它的作用就是為了控制程序的執(zhí)行過程。
import unittest
class Test(unittest.TestCase):
def setUp(self):
num = input('please input a number:')
self.num = int(num)
def test_case(self):
self.assertEqual(self.num,12,msg='wrong! number is not 12')
def tearDown(self):
pass
if __name__ == '__main__':#控制程序的執(zhí)行過程
unittest.main()
要理解它使用方法,需要知道:.py文件是可以直接執(zhí)行,就像一個程序一樣;另外,.py文件也可以作為模塊被導(dǎo)入,使用import語句就能實現(xiàn)。
所以,python中if __ name __ == '__ main__':語句就是為了判斷.py文件執(zhí)行的方式,它是直接執(zhí)行,還是說被作為模塊導(dǎo)入后執(zhí)行,從而控制執(zhí)行的過程。下面用實例進行說明:
二、python實例說明
1、python中__ name __方法
首先,需要了解 __ name__ 是屬于 python 中的內(nèi)置類屬性,就是它會天生就存在與一個 python 程序中,代表對應(yīng)程序名稱。
比如所示的一段代碼里面(這個腳本命名為 test.py),我只設(shè)了一個函數(shù),但是并沒有地方運行它,所以當(dāng) run 了這一段代碼之后我們有會發(fā)現(xiàn)這個函數(shù)并沒有被調(diào)用。
但是當(dāng)我們在運行這個代碼時這個代碼的 __ name__ 的值為 __ main__ (一段程序作為主線運行程序時其內(nèi)置名稱就是 __ main__)。
2、直接執(zhí)行程序
創(chuàng)建一個.py文件,文件名為test.py,直接執(zhí)行程序
print('hello world')
print(f"the test.py __name__ is :{__name__}")
if __name__ == '__main__':
print("repeat! hello world")
結(jié)果:
hello world
the test.py __name__ is :__main__#段程序作為主線運行程序時其內(nèi)置名稱就是 __main__
repeat! hello world
此時,直接執(zhí)行程序時,它作為主線運行程序時其內(nèi)置名稱就是 main
3、作為模塊導(dǎo)入執(zhí)行
創(chuàng)建一個.py文件,文件名為import_test.py,在程序中將test.py作為模塊導(dǎo)入
import test
print('this is import_test')
print(f"the import_test.py __name__ is :{__name__}")
結(jié)果:
hello world
the test.py __name__ is :test #當(dāng)這個 test.py 作為模塊被調(diào)用時,則它的 __name__ 就是它自己的名字
this is import_test
the import_test.py __name__ is :__main__
此時,test.py中的__ name __ 變量值為test,不滿足__ name __ =="__ main__"的條件,因此,無法執(zhí)行其后的代碼“repeat! hello world”。
總之,在程序主體中,我自己就是(__ main__ ),我自己叫我自己那就是我(__ main__),若別人要引用我或者叫我,那就不能再用我了,應(yīng)該叫我的真實名字(test.py),不然誰能分別你。