python, if __name__ = '__main__' role

python, IF the __name__ = '__main__' role

 

Foreword

First of all we need to know in python which all things are objects, modules also are objects, and all modules have a built-in attribute __name__.

__Name__ value of a module depends on how the application module.

If you import a module ( call ) , then the module __name__ value is usually module file name, without the path or file extension.

But it may be like a standard sample procedure run the module directly, in this case, the __name__ the default value will be a special "__main__".

 

Now, we return to this issue in python if __name__ = '__main__' role in the end doing it?

There is a saying classic summarizes the meaning of this code:

“Make a script both importable and executable”

Meaning that let you write a script module can either be imported into other modules used, in addition to the modules themselves also perform .

 

test.py

def main():
    print("we are in %s"%__name__)
if __name__ == '__main__':
    main()

 

Two execution main () function of the way:

Direct execution:

We direct the implementation of some of the py file found the results to print out "we are in __main__", explained the content of our if statement is executed, call the main () .

 

Import ( call ) :

We create test1.py

import test
test.main()

Now I import a module from the other modules and called once main () function , the result of its implementation are:

“we are in test”

 

to sum up

If, when we are directly execute a .py file, the file then "__name__ == '__main__'" is True, but if we import when the file from another .py file by import, then __name__ the value is the name of our py file instead __main__.

if __name__ == '__main__' determines whether to run the .py file directly. This feature is also a useful: debug code, we add some debugging code "if __name__ == '__main__'", we can let the call when the external module does not perform our debugging code, but if we want to troubleshoot when the issue of direct implementation of the module file, debug code to run properly!

 

Guess you like

Origin www.cnblogs.com/-wenli/p/10951557.html