How do I understand the main function of Python?

Source: Internet
Author: User

Python Empire (ID:PYTHONDG)

Difficulty: Beginner

Demo Environment:
Os:ubuntu 16.04
python:3.6

We often see the following statement when writing Python code. It seems to be the Main function of Python. What does it mean exactly?

if __name__ = = ' __main__ ': print (' Hello World ')

First Python has two concepts, source files :

~/code_house/py_dev$ tree.├──file1.py├──file2.py└──p_main.py

The contents are:

py_main.py

Import File1import file2if __name__ = = ' __main__ ': print (file1) print (file2) print (file1.__name__) print (file2 . __name__) Print (__name__) #py_main

Both file1.py and file2.py are empty, and then look at the effect of the operation:

~/code_house/py_dev$ python3 p_main.py <module ' file1 ' from '/home/xinwen/code_house/py_dev/file1.py ' >< Module ' file2 ' from '/home/xinwen/code_house/py_dev/file2.py ' >file1file2__main__

You can see the import of the file printed results are no longer a file but module

Print (file1): <module ' file1 ' from '/home/xinwen/code_house/py_dev/file1.py ' >print (file2): <module ' file2 ' From '/home/xinwen/code_house/py_dev/file2.py ' >

This is the form in which the Python source file is loaded into memory, and it exists in the form of a Python module.

and the name of the **module * * is also the name of the Python source code file:

Print (file1.__name__) file1print (file2.__name__) file2

Typically, the module name in memory is the corresponding file name. But one situation is different, when the file is used as a startup file, or the first file that is executed, the name of the module in memory generated by the file is no longer its file name:

Print (__name__) #py_main__main__

Unity is main .



This article from the "front-end people's Python Empire" blog, reproduced please contact the author!

How do I understand the main function of Python?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.