其实if __name__ == "__main__":很容易理解,
当模块被接运行时,即不调用直接在本脚本中运行,模块 __name__名就为 __main__ ,后面的代码块将被运行。如下:
#first.py
print("新年快乐!猪事大吉!")
def test1():
print("很简单的啦啦啦!")
if __name__=="__main__":
test1()
print("西安年,最中国!")
结果:
当模块是被导入时,代码块不被运行,如下,新建second.py,只输入一句话:
#second.py
import first