if __name__ == ‘__main__‘ 是个什么鬼?

有句话经典的概括了这段代码的意义:

"Make a script both importable and executable"

意思就是说让你写的脚本模块既可以导入到别的模块中用,另外该模块自己也可执行。

咋一看,其实我也不理解到底是个什么球意思,这里我们写两个Demo

test01.py

复制代码
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 导入模块
import test02


def show():
    print('test01')


if __name__ == '__main__':
    show()

test02.py

复制代码
#!/usr/bin/python
# -*- coding: UTF-8 -*-


def show():
    print('test02')


if __name__ == '__main__':
    show()

这里我们运行test01.py,会输出test01。

如果我们吧test02.py修改为:

复制代码
#!/usr/bin/python
# -*- coding: UTF-8 -*-


def show():
    print('test02')



show()

再次执行test01.py,它会输出test01 和 test02。

看到这里小伙伴应该明白了吧,在多模块编程的时候,一定要加入if name == 'main ':

这样一个判断,否则引入模块的方法也会被执行。

相关推荐
邪修king5 分钟前
Re:Linux 系统篇(三十四):进程间通信开篇Chapter1 —— 匿名管道 pipe 深度拆解与代码实战
android·linux·运维·开发语言
花间相见11 分钟前
【计算基础|网络04】—— HTTP接口实战(下):接口测试、鉴权与跨域排错
java·linux·人工智能·后端·python·计算机网络·postman
慧都小项11 分钟前
Python 跨文件重构怎么验证?PyCharm 用法查找、重构预览与测试流程
python·重构·pycharm·单元测试
SEO_juper15 分钟前
2026年用Python批量审计XML Sitemap:揪出sitemap.xml中的“配置错误/死链/过期页“(附完整代码)
java·python·seo·外贸独立站·谷歌优化
钱栈up21 分钟前
自动化多平台发布:脚本报FAIL时用三个信号判断真实状态
python
余槐i21 分钟前
拆解 Agent 核心原理|从零动手实现简易 AI 智能体(三)
人工智能·python·fastapi·ai agent
程序员AlbertTu26 分钟前
# Mantissa 使用教程 — Python 版与 C++ 版
c++·python·数值运算
孙启超28 分钟前
【AI开发之Rust】第 13 课:async/await 与 tokio 异步运行时
开发语言·后端·rust