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

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

相关推荐
QH139292318807 小时前
# R&S ZNB43 ZNA43 ZNA67矢量网络分析仪
开发语言·网络·php
旋生万物7 小时前
电磁力 = 螺旋联络的 90° 旋转?麦克斯韦方程组的几何重构
人工智能·python·算法·机器学习·copilot·世界模型·物理ai
久久学姐7 小时前
【AI问答】python引入其他模块的对象
python·绝对导入·相对导入·目录结构·模块导入
脚踏实地皮皮晨7 小时前
003003001_Grid控件
开发语言·windows·算法·c#·visual studio
十年磨剑走天涯8 小时前
C++ STL 容器操作复杂度速查表
开发语言·c++
always_TT8 小时前
【Python requirements.txt 依赖管理】
开发语言·python
15Moonlight8 小时前
C++进阶(09):特殊类设计
开发语言·c++
宁风NF8 小时前
JavaScript:网络请求与前端通信
开发语言·前端·javascript·网络·学习·ecmascript
Logintern098 小时前
py文件开头为什么需要加:from __future__ import annotations
开发语言·python
bamb008 小时前
一个项目带你入门AI应用开发05
python