作用:当模块被直接运行时,以下代码块将被运行,当模块是被导入时,代码块不被运行。

例子:

# 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")

# file two.py
import one

print("top-level in two.py")
one.func()

if __name__ == "__main__":
    print("two.py is being run directly")
else:
    print("two.py is being imported into another module")

如果你执行one.py文件,

python one.py
会输出:

top-level in one.py
one.py is being run directly
如果你执行two.py文件,

python two.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

 总结:当模块导入时if __name__ == "__main__" 代码块不被执行,写if __name__ == "__main__"是为了防止模块导入,导致又重新运行了一遍导入的模块的代码。

相关文章:

  • 2022-12-23
  • 2022-01-13
  • 2021-08-25
  • 2021-11-03
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-03
  • 2022-12-23
  • 2022-12-23
  • 2021-12-22
  • 2022-01-17
  • 2021-11-18
  • 2021-08-22
相关资源
相似解决方案