Discuss / Python / __name__=='__main__'

__name__=='__main__'

Topic source

卧龙河泊

#1 Created at ... [Delete] [Delete and Lock User]

if name=='main': test()

这句话是什么意思啊?

SORRY, CANNOT TYPE CHINESE HERE, FOUND ANSWER FROM STACKOVERFLOW HOPE IT CAN BE HELPFUL


*"if the python interpreter is running that module (the source file) as the main program, it sets the special name variable to have a value "main". If this file is being imported from another module, name will be set to the module's name."


This is why when we run hello.py directly, we can see the "helloworld" directly. If we import it, the name special variable actually not equal to main. thats why we cannot run test() function directly when we import hello.py module

H_ymin

#3 Created at ... [Delete] [Delete and Lock User]

也就是说当直接运行hello.py的时候name就是main,而当从别的模块import Hello.py的时候,name被设置成了"Hello.py"对吗?如果这样的话,不知道这个功能有什么用呢?

搜嘎

宁康NK

#5 Created at ... [Delete] [Delete and Lock User]

name=='main'的作用作者说的很明白了。

简单的说,你程序里面的代码是这样的:

if name=='main':

test()

当你直接运行文件hello.py时,这时系统给一个特殊变量name设置成main,这样进入文件后,if语句就能执行下去,接着就自动执行test()

而当你导入模块hello.py时,系统这时不会有给name设置成main这个动作,所以if语句就判断不下去,也就没法执行test()这个函数,这时你就只能自己调用这个函数了:hello.test()


  • 1

Reply