if __name__ == '__main__':This is a commonly used conditional statement in Python that allows a Python file to be executed as an independent script or imported as a module by other Python scripts. Specifically, when a Python file is executed as a script,if __name__ == '__main__':The following code block will be executed; this occurs when the file is imported by another Python script.if __name__ == '__main__':The following code block will not be executed.
For example, suppose we have two Python files:script.py和module.py。script.pyIt is an executable script file, whilemodule.pyIt is a Python file that can be imported as a module. Thus, we canscript.pyWrite it like this:
import module
if __name__ == '__main__':
# 以下是脚本文件的执行代码
# ...In this example, wescript.pyIntroduced into ChinamoduleModule – Useif __name__ == '__main__':Determine whether to execute the code block that contains a script file. Whenscript.pyWhen executed as a script,if __name__ == '__main__':The following code block will be executed; and whenmodule.pyWhen imported by other Python scripts,if __name__ == '__main__':The following code block will not be executed.
Useif __name__ == '__main__':It allows us to write executable scripts and Python files that can be imported as modules more conveniently, thereby enhancing code reusability and maintainability.