首頁  >  文章  >  後端開發  >  關於python中__ name__值的測試詳細介紹

關於python中__ name__值的測試詳細介紹

高洛峰
高洛峰原創
2017-03-19 14:01:481663瀏覽

這篇文章主要介紹關於python中__ name__值的測試詳細介紹

測試中用到的程式碼如下:

#test_name0.py
def test():
    return name

print name
print test()
import test_name1
test_name1.test()
#test_name1.py
def test():
    print name
    
print name

python頂層解釋器中執行指令與結果如下:

In [1]: type(name)
Out[1]: str
In [2]: print name
Out[2]: main
In [3]: import test_name0
test_name0
test_name0
test_name1
test_name1

在cmd中執行python test_name0.py,結果如下:

main
main
test_name1
test_name1

由此可以看出:

(1)在python頂層解釋器或直接運行的腳本中name=='main'

(2)在呼叫的模組中name==<a href="http://www.php.cn/code/8212.html" target="_blank">module</a> name

(3)發現一個非預期的情況,就是在執行了test_name0.py的腳本後再import test_name0,或import test_name0後面再執行test_name0.py的腳本,得到的結果是

test_name0
test_name0
test_name1

main
main
test_name1

#而不是

test_name0
test_name0
test_name1
test_name1

main
main
test_name1
test_name1

將問題的關鍵整理後在segmentfault上提問,了解了出現此問題的原因。
即:python模組有快取,import一次後再import,模組頂級作用域的程式碼不會再執行。

(4)test_name0和test_name1兩個模組中的test函數是同名的,這並不會有沒有什麼問題,因為模組名稱不同而可以區分這兩個test函數,但要避免模組的重名。

以上是關於python中__ name__值的測試詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn