Analysis of if _ name __= = '_ main _' in Python

Source: Internet
Author: User
This article mainly introduces the function parsing of if _ name ____ main _ in Python. this broken code is very common in Python. does it work? This article explains how it works. if you need a friend, you can refer to it when you open. in the py file, if _ name _ = '_ main _' is often displayed at the bottom of the code. now let's introduce its role.

A module is an object, and all modules have a built-in attribute _ name __. The value of _ name _ of a module depends on how you apply the module. If you import a module, the value of module _ name _ is usually the module file name, without the path or file extension. However, you can run a module directly like a standard program. in this case, the value of _ name _ is a special default value "_ main __".

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

Run the. py file directly in cmd, and the value of _ name _ is '_ main __';

After importing A. py file, the value of __name _ is not '_ main;

Therefore, if _ name _ = '_ main _' is used to determine whether the. py file is directly running.

For example:

The code is as follows:

# Test. py

Class Test:

Def _ init (self): pass

Def f (self): print 'Hello, World! '

If _ name _ = '_ main __':

Test (). f ()

# End

In cmd, enter:

The code is as follows:

C:> python Test. py

Hello, World!

Note: "_ name _ = '_ main _'" is true.

In cmd, enter:

The code is as follows:

C:> python

>>> Import Test

>>> Test. _ name _ # Test module's _ name __


>>>__ Name _ # Current program's _ name __

'_ Main __'

In any case, "_ name _ = '_ main _'" in Test. py will not be true!

Therefore, the next line of code will never run!

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