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 ':

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

相关推荐
深蓝AI8 小时前
HTTPX 超时 1 秒,接口为何还能跑 2.4 秒?
python
CyrusYiVPP8 小时前
哪个用户会再来买?RFM模型+plotly画出用户分层,数据分析实战第2期
人工智能·python
李帅51510 小时前
用 CPU 做发票识别:从 OCR 文本行到结构化明细表的 4 个硬骨头
python
happylifetree10 小时前
Python79:核心语法-面向对象基础-实例方法
python
nice_lcj52011 小时前
ThreadLocal 入门:它是怎么隔离数据的、为什么会导致内存泄漏
java·开发语言·后端·面试·并发编程·内存泄漏·threadlocal
贝壳69011 小时前
bool-hybrid-array 9.13.6 偷偷加了个"按键自动升序"的字典,我翻出来测了下
python
紧跟先前的步伐11 小时前
Go AI Agent 实战 28|Agent 的预算、超时与停止条件
开发语言·人工智能·后端·ai·golang
艺杯羹11 小时前
MCP本地服务集成避坑:从Stdio管道僵死到双向JSON-RPC稳健通信
人工智能·python·ai·系统架构·大语言模型·ai编程·mcp
happylifetree11 小时前
Python78:核心语法-面向对象基础-类与对象
python
duansamve11 小时前
Python中进程
python