“if __name__ == __main__:”的作用:指定主方法函数。在脚本执行时开启main函数,但是在其他文件import调用时不会执行。

一个python的文件有两种使用的方法,第一是直接作为脚本执行,第二是在其他文件的python脚本中被import即调用(模块重用)执行。因此if name == 'main':的作用就是控制这两种情况执行代码的过程,在if name == 'main':下的代码只有在第一种情况下(即文件作为脚本直接执行)才会被执行,而import到其他脚本中是不会被执行的。
例子:
# file one.pydef 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.pyimport one # start executing one.pyprint("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")当运行python one.py,输出:
top-level in one.py one.py is being run directly
当运行python two.py,输出:
top-level in one.py one.py is being imported into another module top-level in one.pyfunc() in one.py two.py is being run directly
以上就是“if __name__ == __main__:”有什么作用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号