introduce
__name__
is a special built-in variable in Python that determines whether a Python file is run directly or imported as a module.
When the file is imported as a template, its __name__ attribute value is automatically set to the module name
. When the file is run directly as a program, its __name__ attribute value is automatically set to the string " main " .
code
Here's a __name__
sample code detailing usage, with detailed comments:
# 定义一个简单的函数
def my_function():
print("这是一个函数!")
# 如果脚本是被直接运行的,__name__ 的值将是 '__main__'
if __name__ == '__main__':
print("这个脚本正在直接运行。")
# 在这里可以添加任何您想要在直接运行时执行的代码
# 调用定义的函数
my_function()
# 如果脚本是被导入为模块的,__name__ 的值将是模块的名称(在导入时由 Python 解释器分配)
else:
print("这个脚本被用作一个模块。")
# 在这里可以添加任何您希望在脚本被导入时执行的代码
# 注意:在此处定义的代码将在脚本直接运行或作为模块导入时执行,具体取决于 __name__ 的值。
The explanation is as follows:
-
First, a simple function is defined
my_function()
that will print a message. -
Use
if __name__ == '__main__':
to check__name__
if the value of is'__main__'
. If it is, it means the script is running directly, so the code block under this condition will be executed. -
if __name__ == '__main__':
Under , you can place the code you want to execute when the script is run directly. -
Then, check
__name__
if is equal to the name of the module. If the script was imported as a module, the value__name__
of will be the name of the module, otherwise, if the script was run directly .__name__
'__main__'
-
Under
else:
the branch, you can put code that you want executed when the script is imported as a module.
This way of using __name__
can make your script more reusable because it can execute different blocks of code in different contexts while avoiding the duplication of unnecessary code.