Python usage of name main

Source: Internet
Author: User

_ Name __:

When using itself, it is main, for example, you execute:
Python test. py
The name in test. py is main.
If you import test in test2, then name is the file name http://www.cnblogs.com/herbert/archive/2011/09/27/2193482.html

I have seen many python codes with this code:

If _ name _ = '_ main _': The main function of this Code is to allow the python file to run independently, it can also be imported to other files as a module. When importing to other script files, the main code will not be executed. Reference: http://pyfaq.infogami.com/tutor-what-is-if-name-main-for The if _ name _ = "_ main __":... trick exists in Python so that our Python files can act as either reusable modules, or as standalone programs. as a toy example, let's say that we have two files:

Mumak :~ Dyoo $ cat mymath. py
Def square (x ):
Return x * x

If _ name _ = '_ main __':
Print "test: square (42) =", square (42)


Mumak :~ Dyoo $ cat mygame. py
Import mymath

Print "this is mygame ."
Print mymath. square (17) In this example, we 've written mymath. py to be both used as a utility module, as well as a standalone program. we can run mymath standalone by doing this:

Mumak :~ Dyoo $ python mymath. py
Test: square (42) = 1764But we can also use mymath. py as a module; let's see what happens when we run mygame. py:

Mumak :~ Dyoo $ python mygame. py
This is mygame.
289 Notice that here we don't see the 'test' line that mymath. py had near the bottom of its code. that's because, in this context, mymath is not the main program. that's what the if _ name _ = "_ main __":... trick is used.

 

In this example, when the square function is called in mygame. py, the main function in mymath. py is not executed.

Related Article

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.