Usage and explanation of __name__ in Python

Insert image description here

Article directory

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:

  1. First, a simple function is defined my_function()that will print a message.

  2. 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.

  3. if __name__ == '__main__':Under , you can place the code you want to execute when the script is run directly.

  4. 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__'

  5. 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.

Guess you like

Origin blog.csdn.net/weixin_74850661/article/details/132656651