Before understanding of this is:
__name__ == IF "__main__": # this time you can execute the program
method one:
This is in your own eye, you think you are __main__
For example
print('hello world!') print('__name__value:',__name__) def main(): print('This message is from main function') if __name__ == "__main__": main()
Code is executed, the output
hello world! __name__value: __main__ This message is from main function
We can get analysis: At this time __name__ == "__main__"
Therefore, the output of the second sentence __main__
In if __name__ == "__main__": this sentence, apparently set up, we direct the implementation of main (content of the function), the output This message is from main function
And back to a situation
此为print_func.py print('hello world!') print('__name__value:',__name__) def main(): print('This message is from main function') if __name__ == "__main__": main()
Another python file print_module.py
import print_func print("Done!")
This time output Shane?
We analyze: first in print_module.py, that is in the eyes of others, __ name__ == "print_func", no longer perform print_func.py in if __name__ == "__main__": statement
Then the output
hello world! __name__value: print_func Done!
to sum up
Run their own programs, __ name__ is the __main__
When the program is invoked as a script to run other people, it __name__ for their module name, print_func here are imported into print_module as the script is running, the print_func of __name__ That becomes its own module name.