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

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

相关推荐
AI创界者6 小时前
Python 进阶实战(七十章):遗留系统重构、渐进式绞杀与技术债治理实战
人工智能·python·aigc
ZhengEnCi7 小时前
电脑操作 Agent 一直点不中:截图没更新时,提示词该怎么改才能停止瞎试
人工智能·python·agent
郝学胜-神的一滴8 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
Wellijohn9 小时前
dict、tuple、dataclass 还是 slots?我把 6 种数据载体的 8 项开销全测了一遍
后端·python·性能优化
bufengwangluo10 小时前
爬虫和调用 API 有什么区别?为什么优先选 API
python·网络爬虫·ip·api调用
Dmz丶10 小时前
前端转 AI 100 天 Day 54:RAG 项目实战(三)——多轮对话 + 会话管理
python
console.log('npc')10 小时前
Python第9课 类学习笔记,前端js语法对照
前端·python·学习
geovindu12 小时前
python:Logistic Regression
开发语言·后端·python·算法