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

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

相关推荐
VIP_CQCRE22 分钟前
用 Ace Data Cloud 快速接入 OpenAI Chat Completions:对话、流式、多轮和多模态一篇打通
python·ai·openai·api·教程
老迟到的茉莉1 小时前
Hermes 是谁?跟 Claude Code 差在哪
开发语言·python
学逆向的1 小时前
汇编——内存
开发语言·汇编·算法·网络安全
Day(AKA Elin)1 小时前
【Day】MTP(Multi Token Prediction)技术学习
python·深度学习·学习·llama
lbb 小魔仙2 小时前
MuMu 模拟器 6.0 硬核测评:这次升级确实不一样
java·开发语言·模拟器·mumu·硬核测评
r_oo_ki_e_2 小时前
Java 线程池
java·开发语言
杜子不疼.2 小时前
【Qt初识】信号槽(二):自定义信号函数与槽函数
开发语言·qt
程序员小远3 小时前
接口测试之文件上传
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
ctrl_v助手3 小时前
C#日志工具类log4net的使用
开发语言·c#
秋田君3 小时前
Qt_QVariant
开发语言·qt