当python解释器读一个源文件的时候,会执行文件里面全部的代码。可是若是python执行一个源文件,做为main program执行的时候,会设置一个__name__变量,这个变量的值为__main__. 当执行主程序的时候使用 if __name == '__name__', 若是值为true,那么python会执行该文件,不论是做为可重复使用的模块或者是一个单独的程序。python
若是要python在执行import文件种的函数:函数
__name __== moudle's namespa
例如:code
test1.pyblog
from test2 import print_hello def print_world(): print ('world') if __name__ == '__main__': print_world() print_hello()
test2.pyclass
def print_hello(): print ('hello') if __name__ == 'test2': print_hello()
单独运行test2.py 无任何打印, 由于没有__name__ == '__main__'test
若是运行test1.py, 则会打印hello,word,hello , 首先在import的时候会运行test2.py,而后再运行__name__=='__main__'下的两个函数。import
若是要python执行本文件种的函数:变量
__name __== '__main__'程序