python - __name__= __main__怎么解释 怎么用 另外两个py文件之间的互动关联
巴扎黑
巴扎黑 2017-04-18 10:25:24
0
4
727

name = '__main__' 的作用
有句话经典的概括了这段代码的意义:

“Make a script both importable and executable”

意思就是说让你写的脚本模块既可以导入到别的模块中用,另外该模块自己也可执行。
def foo():
    print('in foo')
print(__name__)
foo()
if __name__=='__main__':
    foo()
返回结果
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")
结果:
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")
结果:
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模块被导入的话,ob05模块中的__name__=__main__
解释错或不对不完善 麻烦完善下 
那import是干嘛用呢,就引入了一个func()?name == "__main__" 是什么意思 起什么作用

巴扎黑
巴扎黑

reply all(4)
大家讲道理

To put it simply, you can write a paragraph in every Python code file

if __name__ == '__main__':
    doSomething()

The dosomething here will only be called when you execute this file directly in the terminal, and will not be called when you import it as a package to other files and execute that file.

Peter_Zhu

This is how to understand if name == 'main' in python:
https://github.com/pythonpeix...

Ty80

__name__: Indicates the name of module, class, etc.;

__main__: represents the module, the xxx.py file itself.

    When
  • is executed directly, the corresponding module name is __main__. You can add the code you want in if __name__ == “__main__”: for testing the module, demonstrating module usage, etc.

  • As a module, when it is imported elsewhere, the module name is the file name xxx.

小葫芦

Function has two main functions: 1. Code reuse. 2. Process decomposition. This means that when you write other programs, you may call the function you are writing now. After writing a function, we need to test the function or do some work with it, then we write what we want to do in if __name__=='__main__':. When you write another program to call this module the next day, it will execute the function in front of if __name__=='__main__':, but not the code inside if __name__=='__main__':.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!