What does 'if __name__ == __main__:' do?

anonymity
Release: 2020-09-18 09:24:01
Original
13784 people have browsed it

The role of "if __name__ == __main__:": specifies the main method function. The main function is started when the script is executed, but will not be executed when other files are imported.

What does 'if __name__ == __main__:' do?

There are two ways to use a python file. The first is to execute it directly as a script, and the second is to be imported in the python script of other files. Call (module reuse) execution. Therefore, the function of if name == 'main': is to control the process of executing the code in these two situations. The code under if name == 'main': can only be executed in the first situation (that is, the file is directly executed as a script). will be executed, but importing it into other scripts will not be executed.

Example:

# 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")
Copy after login
# file two.pyimport one        # start executing one.pyprint("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")
Copy after login

When running python one.py, the output is:

top-level in one.py
one.py is being run directly
Copy after login

When running python two.py, the output is:

top-level in one.py
one.py is being imported into another module
top-level in one.pyfunc() in one.py
two.py is being run directly
Copy after login

The above is the detailed content of What does 'if __name__ == __main__:' do?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template