欢迎来到赛兔子家园

Python中的__name__ == '__main__'详解

在Python中,__name__='__main__'的作用主要是用于区分一个Python脚本是直接运行还是被导入到其他模块中。‌

基本概念

当Python脚本直接运行时,__name__变量的值被设置为__main__。当该脚本被其他脚本导入时,__name__的值则被设置为该脚本的模块名。利用这一特性,可以在脚本中编写条件语句,以决定某些代码块仅在脚本直接运行时执行,而在被导入时不执行。

使用场景

1、模块测试‌:在开发模块时,经常需要测试模块中的函数或类。通过使用if __name__ == '__main__':,可以在模块的底部添加测试代码,这些测试代码只有在模块直接运行时才会执行,从而方便进行模块的独立测试。
2‌、避免重复执行‌:在某些情况下,我们不希望模块中的某些操作在每次导入时都执行,尤其是在涉及到资源加载或初始化操作时。通过使用if__name__=='__main__':,可以确保这些操作仅在模块首次运行时执行一次。

示例代码

下面是一个简单的示例,展示了如何使用__name__='__main__'来区分脚本的直接运行和模块导入:

def my_function():
    print("This function is defined in the module.")

if __name__ == '__main__':
    print("This code block will only execute when the script is run directly, not when it's imported.")
    my_function()
else:
    print("This code block will execute when the script is imported into another script.")

在这个示例中,当脚本直接运行时,会打印一条消息并调用my_function()函数。如果该脚本被导入到另一个脚本中,则只会打印另一条消息。

posted on 2024-11-25 09:42  赛兔子  阅读(75)  评论(0)    收藏  举报

导航