What does __init__ == __main__ mean?
来源:互联网 发布:单片机的http编程 编辑:程序博客网 时间:2024/06/05 21:53
When your script is run by passing it as a command to the Python interpreter,
python myscript.py
all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets ran. Unlike other languages, there's no main()
function that gets run automatically - the main()
function is implicitly all the code at the top level.
In this case, the top-level code is an if
block. __name__
is a built-in variable which evaluate to the name of the current module. However, if a module is being run directly (as in myscript.py
above), then __name__
instead is set to the string "__main__"
. Thus, you can test whether your script is being run directly or being imported by something else by testing
if __name__ == "__main__": ...
If that code is being imported into another module, the various function and class definitions will be imported, but the main()
code won't get run. As a basic example, consider the following two scripts:
# file one.pydef func(): print("func() in one.py")print("top-level in one.py")if __name__ == "__main__": print("one.py is being run directly")else: print("one.py is being imported into another module")# file two.pyimport oneprint("top-level in two.py")one.func()if __name__ == "__main__": print("two.py is being run directly")else: print("two.py is being imported into another module")
Now, if you invoke the interpreter as
python one.py
The output will be
top-level in one.pyone.py is being run directly
If you run two.py
instead:
python two.py
You get
top-level in one.pyone.py is being imported into another moduletop-level in two.pyfunc() in one.pytwo.py is being run directly
Thus, when module one
gets loaded, its __name__
equals "one"
instead of __main__
.
- What does __init__ == __main__ mean?
- What does 'if __name__=='__main__' do
- What does => and () => mean in Scala
- what does boinc mean?
- what does "ERP" mean
- What does "V"mean
- What does "Vanilla" mean ?
- what href="#" mean?
- What does 2>&1 mean?
- What does _imp_<Function> mean?
- What does operator “dot” (.) mean?
- What does AspCompat="true" mean and when should I use it?
- What does it mean to write `static void * ptr = &ptr` in objective-c?
- What does mean RSS, Atom, OPML...?
- What does Keyword-Driven Testing mean?
- What does TCP Zero Window mean?
- What does (Aborted) mean in HttpWatch?
- What does "#! /usr/bin/ksh" mean?
- 黑马程序员------OC类的封装 继承 多态
- 基于StoryBoard自动布局--Cell自适应高度
- 如何获取当前日期,如何格式化日期输出?
- swift学习之元组
- JAVA学习的第二天感想
- What does __init__ == __main__ mean?
- 字符设备驱动
- DIY 一个 JSON解析器。
- pagerAdapter的不同使用方法
- gulp的使用
- 【ZOJ 3874】Permutation Graph
- Leetcode: Isomorphic Strings
- Linux环境编程资源总结
- Python下配置LibSVM