python下面代码是什么_python代码下面__name__= __main__怎么使用 作用是什么?
name = '__main__' 的作用
有句話經(jīng)典的概括了這段代碼的意義:
“Make a script both importable and executable”
意思就是說讓你寫的腳本模塊既可以導(dǎo)入到別的模塊中用,另外該模塊自己也可執(zhí)行。
def foo():
print('in foo')
print(__name__)
foo()
if __name__=='__main__':
foo()
返回結(jié)果
main ? 意思是__name__=__main,所以if語句判斷True。
ob05.py
def func():
print("func() in ob05.py")
print("top-level in ob05.py")
if name == "__main__":
print("ob05.py is being run directly")
else:
print("ob05.py is being imported into another module")
結(jié)果:
top-level in ob05.py
ob05.py is being run directly
ob06.py
import ob05
print("top-level in ob06.py")
ob05.func()
if name == "__main__":
print("ob06.py is being run directly")
else:
print("ob06.py is being imported into another module")
結(jié)果:
top-level in ob05.py
ob05.py is being imported into another module
top-level in ob06.py
func() in ob05.py
ob06.py is being run directly
Thus, when module one gets loaded, its name equals "one" instead of __main__.
意思是ob05模塊被導(dǎo)入的話,ob05模塊中的__name__=__main__
解釋錯(cuò)或不對(duì)不完善 麻煩完善下
那import是干嘛用呢,就引入了一個(gè)func()?name == "__main__" 是什么意思 起什么作用
簡(jiǎn)單來說就是每一個(gè)Python代碼文件里都可以寫上一段if __name__ == '__main__':
doSomething()
這里的dosomething只會(huì)在你直接在終端執(zhí)行這個(gè)文件的時(shí)候會(huì)被調(diào)用,而不會(huì)在作為包import到其他文件并執(zhí)行那個(gè)文件時(shí)調(diào)用。
__name__:表示模塊,類等的名字;
__main__:表示模塊,xxx.py文件本身.
函數(shù)有兩個(gè)主要作用:1、代碼重用。 2、過程分解。這就意味這你寫別的程序的時(shí)候可能會(huì)調(diào)用現(xiàn)在寫的這個(gè)函數(shù)。編寫好一個(gè)函數(shù)后,我們需要測(cè)試這個(gè)函數(shù)或者用它做一些工作,那我們就把要做的事情寫在 if __name__=='__main__': 里面 。二天你寫別的程序調(diào)用這個(gè)模塊的時(shí)候,它會(huì)執(zhí)行 if __name__=='__main__':前面的函數(shù),而不會(huì)執(zhí)行if __name__=='__main__':里面的代碼。
玩蛇網(wǎng)文章,轉(zhuǎn)載請(qǐng)注明出處和文章網(wǎng)址:https://www.iplaypy.com/wenda/wd13765.html
相關(guān)文章 Recommend
總結(jié)
以上是生活随笔為你收集整理的python下面代码是什么_python代码下面__name__= __main__怎么使用 作用是什么?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql脚本文件长什么样_在linux
- 下一篇: websocket python爬虫_p