If in Python

Source: Internet
Author: User
Tags in python

This article mainly introduces Python if __name__ = = ' __main__ ' function parsing, which is very common in Python, does it work? This article has analyzed its function, needs the friend to be possible to refer to under

When you open a. py file, you will often see the 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 attribute __name__. The value of a module's __name__ depends on how you apply the module. If you import a module, the module __name__ value is usually the module file name, without the path or file name extension. But you can also run the module like a standard program sample directly, in which case the __name__ value will be a special default "__main__".

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

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

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

Then use if __name__ = = ' __main__ ' to determine if the. py file is being run directly

Such as:

The code is as follows:

#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:

The code is as follows:

C:>python test.py

Hello, world!.

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

You enter in cmd again:

The code is as follows:

C:>python

>>>import Test

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

' Test '

>>>__name__ #当前程序的__name__

' __main__ '

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

So the next line of code never runs to!

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.