python中的__name__ == "__main__"
时间: 2023-09-24 07:13:15 浏览: 101
在Python中,`__name__ == "__main__"`是一个常见的用法,用于判断一个.py文件是被直接执行还是被作为模块导入。当一个.py文件被直接执行时,`__name__`的值会被设置为`"__main__"`,而当它被作为模块导入时,`__name__`的值会是模块的名称。这个用法通常被用于将一些只有在直接执行时才需要执行的代码放在一个条件语句块中,以避免在模块导入时执行这些代码。通过使用`__name__ == "__main__"`这个条件,我们可以在一个.py文件中同时包含可执行代码和模块导入所需的代码,以提高代码的可重用性和模块化程度。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Python中if __name__ == ‘__main__‘用法及原理解析](https://blog.csdn.net/DALEONE/article/details/122267822)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [一文弄懂Python中的 if __name__ == __main__](https://blog.csdn.net/sgzqc/article/details/124849467)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文