時(shí)間:2023-01-31 13:28:01 | 來(lái)源:建站知識(shí)
時(shí)間:2023-01-31 13:28:01 來(lái)源:建站知識(shí)
作者:leetaoif __name__ == '__main__': func_name()
那么這一行代碼有什么具體的作用呢,不加的話會(huì)對(duì)我們的結(jié)果造成影響嗎?__name__
__name__
,我們常見(jiàn)的還有 __init__
,__dict__
等等.那么有多少內(nèi)置變量呢?我們可以通過(guò)下面在交互界面輸入下面的命令,查看 Python 全部?jī)?nèi)置變量和內(nèi)置函數(shù)>>> dir(__builtins__)
結(jié)果如下圖:__name__
的值__name__
在不同情況下會(huì)有不同值,它的值取決于我們是如何執(zhí)行腳本的.我們可以通過(guò)幾個(gè)例子感受一下:# test.pyprint(f'__name__ 在 test.py 值為 {__name__}')
然后直接執(zhí)行一下代碼$ python test.py
然后看一下輸出$ python test.py __name__ 在 test.py 值為 __main__
在這個(gè)例子中,我們發(fā)現(xiàn) __name__
的值是 __main__
# test1.pyimport testprint(f'__name__ 在 test1.py 值為 {__name__}')
接著執(zhí)行一下 test1.py,再看一下輸出python test1.py __name__ 在 test.py 值為 test__name__ 在 test1.py 值為 __main__
結(jié)果是不是很有意思?整個(gè)過(guò)程是什么樣子的呢?簡(jiǎn)單的畫了一個(gè)圖__name__
__name__
了. 這里通過(guò)改造上面 Example 1的例子來(lái)直觀感受一下# test.pydef hello(name): print(f'Hello,{name}') if __name__ == '__main__': hello("test")
再修改一下 test1.py 文件# test1.pyfrom test import hellohello("test1")
然后讓我們先嘗試直接運(yùn)行一下 test.py
,很顯然這個(gè)時(shí)候, if 語(yǔ)句條件滿足,會(huì)輸出 Hello,test$ python test.py Hello,test
這個(gè)時(shí)候我們?nèi)绻\(yùn)行 test1.py
,程序就會(huì)輸出 Hello,test1 了$ python test1.py Hello,test1
如果我們把 if __name__ == "__main__"
在 test.py
去掉會(huì)發(fā)生什么呢?$ python test1.py Hello,testHello,test1
__name__
, and then__name__
checks we always see in Python scripts.foo.py
.# Suppose this is foo.py.print("before import")import mathprint("before functionA")def functionA(): print("Function A")print("before functionB")def functionB(): print("Function B {}".format(math.sqrt(100)))print("before __name__ guard")if __name__ == '__main__': functionA() functionB()print("after __name__ guard")
__name__
variable.python foo.py
the interpreter will assign the hard-coded string "__main__"
to the __name__
variable, i.e.# It's as if the interpreter inserts this at the top# of your module when run as the main program.__name__ = "__main__"
When Your Module Is Imported By Another# Suppose this is in some other main program.import foo
The interpreter will search for your foo.py
file (along with searching for a few other variants), and prior to executing that module, it will assign the name "foo"
from the import statement to the __name__
variable, i.e.# It's as if the interpreter inserts this at the top# of your module when it's imported from another module.__name__ = "foo"
關(guān)鍵詞:
客戶&案例
營(yíng)銷資訊
關(guān)于我們
客戶&案例
營(yíng)銷資訊
關(guān)于我們
微信公眾號(hào)
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。