A brief analysis of _name_= ' _main_ ' in Python

Source: Internet
Author: User

Just contact Python, the code in the _name_= ' _main_ ' more confused, this article on its explanation for reference to other blog (see Resources), I hope and everyone together to learn.

Make a script both importable and executable

First, let's look at an example.

1 # module.py 2 def Main (): 3   Print " we is in%s "%__name__4if__name__'__main__ ' : 5   Main ()

In this function, the main function is defined, and when the py file is executed, the We is in __main__ is printed, indicating that the contents of the IF statement are executed. However, when you import a module module from another module and call Main ()

1 # anothermodule.py 2  from Import Main 3 Main ()

Will print the results we are in module

The number is different from the previous display, stating that there is no code to enter if

where __name__ is the built-in property of the module, and the value of this built-in property depends on how the. py file is used, whether it is imported as a module or executed directly.
If you are directly executing, then the value of this __name__ is __main__, if you import as a module, then this built-in property value depends on the file name, here is the module.

Resources

1.http://blog.csdn.net/sinat_15274667/article/details/51378882

2.http://www.jb51.net/article/51892.htm

A brief analysis of _name_= ' _main_ ' in 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.