Python-based python if __name__ = = ' __main__ ': parsing

Source: Internet
Author: User

When you open a. py file, you will often see if __name__ = = ' __main__ ' at the bottom of the code: Now let's introduce its role.

The module is an object, and all modules have a built-in property of __name__. The value of the __name__ of a module depends on how you apply the module. If you import a module, the value of the module __name__ is usually the module file name, without the path or file extension. But you can also run the module directly like a standard program, in which case the __name__ value will be a special default "__main__".

///////////////////////////////////////////////////////////////////////////////////////////////////

Run the. py file directly in cmd, then the value of __name__ is ' __main__ ';

After import a. py file, the value of __name__ is not ' __main__ ';

Thus use if __name__ = = ' __main__ ' to determine whether the. py file is running directly

Such as:

#Test. py

Class Test:

def __init (self):p

def f (self):p rint ' Hello, world! '

if __name__ = = ' __main__ ':

Test (). F ()

#End

You enter in cmd:

C:>python test.py

Hello, world!.

Description: "__name__ = = ' __main__ '" is established

You type in cmd again:

C:>python

>>>import Test

>>>test.__name__ #Test模块的__name__

' Test '

>>>__name__ #当前程序的__name__

' __main__ '

No matter what, test.py in the "__name__ = = ' __main__ '" will not be set up!

So, the next line of code will never run to!

//////////////////////////////////////////////////////////////////////////////////

Python-based python if __name__ = = ' __main__ ': parsing

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.