关于if __name__ == '__main__'的解释
if __name__ == '__main__'其中__name__是当前模块的名字,这行代码被用于区别当前代码块是被直接运行还是被导入运行,若是直接运行代码将被直接运行 若被导入 模块不被运行
file 测试1.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”)
file 测试.py
import 测试1
print(“top-level in two.py”)
测试1.func()
if name == “main”:
print(“two.py is being run directly”)
else:
print(“two.py is being imported into another module”)
执行如果你执行测试1.py文件
会输出:
top-level in one.py
one.py is being run directly
如果你执行测试.py文件,
会输出:
top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly