今天在项目中遇见了几次 if name = “main“: 虽然知道这代表着代码的入口,但更具体的信息却并不了解太多,于是 google 了后记录下对此的认识。
python 文件具有两种使用方法:
可以作为一个脚本直接去运行,例如我的第一个’hellow world’ python程序;
也可以作为一个模块被其他文件导入;
而 if name = “main“: 就是为了区分这两种情况避免引起不必要的错误。
举个例子:
/home
——-test:
————-__init__.py
————-test1.py
——-test2.py
#/home/test/test1.py def run(): print("The program is running...") run()12345'
python3 /home/test/test1.py
The program is running...
#/home/test2.py from test import test1 print("i am test2.py")123
python3 /home/test2.py
The program is running...
i am test2.py
看起来是不是很奇怪,test2.py 文件中我只是想打印一句话,但是运行时却将我 test1.py 中函数里的输出也给打印出来了。这是与我们期望是不符的。
下面我们为test1.py修改一下来防止这种情况发生
#/home/test/test1.py def run(): print("The program is running...") if __name__ = '__main__': run()123456
这样再次运行就不会出现上述的情况了。而且作为脚本运行的话也不会出现什么错误。
这样例子一看就能很清楚的知道 if __name__ = ‘__main__’ 的功能了,他就类似于一个入口程序,当是直接运行文件时才会执行下面的语句,否则的话是不执行的。
那么为什么一行简单的代码能够实现这么神奇的作用呢?
我们知道每个模块都包含有一些内置属性,比如 __name__ , 通过这个属性我们可以获得模块名称(不包含 .py 后缀)。当模块是被直接执行的,那么 __name__ 的值就是 ‘main’。所以我们可以借此来判断模块运行时是直接运行的还是作为包被导入的。