if __name__ == "__main__"的理解
转载自https://www.cnblogs.com/lesleysbw/p/5898158.html#undefined
------------以下是转载内容------------
粗略来讲,__name__是当前模块,当模块被直接运行时模块名为__main__。这句话的意思是,当模块被直接执行时,代码将运行,当模块是被导入时,代码不被运行
例如,执行one.py
# file one.py def func(): print("func() in one.py") print("top-level in one.py") if __name__ == "__main__": print("one.py is being run directly") else: print("one.py is being imported into another module")
运行结果:
执行two.py:
# file two.py import one print("top-level in two.py") one.func() if __name__ == "__main__": print("two.py is being run directly") else:
运行结果: