purpose of 'if

This question already has an answer here:

  • What does if __name__ == “__main__”: do? 23 answers

  • Well, imagine that someone else wants to use the functions in your module in their own program. They import your module... and it starts doing its own thing!

    With the if __name__ == "__main__" , this doesn't happen. Your module only "does its thing" if it's run as the main module. Otherwise it behaves like a library. It encourages code reuse by making it easier.

    (As @Sheng mentions, you may want to import the module into another script yourself for testing purposes.)


    The if __name__ == '__main__' convention in python is intended to allow you to write code that can be run directly, or imported. If you import it, that if block is not executed. If you run python.exe myscript.py it is.


    This is the idiomatic way to tell whether the Python module was executed as a script, or imported from another module. You will only enter the if __name__ == "__main__" block if the file was executed as a script (aka, it is the main module).

    链接地址: http://www.djcxy.com/p/1602.html

    上一篇: 在Python中,什么是全局声明?

    下一篇: 目的'如果