作者:leetao

链接:【Python】__name__ 是什么?

来源:博客园

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

前言

在我们浏览一下 python 文件或者自己写 python 代码的时候,时常会在代码的最后加上这样的一行代码

if __name__ == '__main__':func_name()

那么这一行代码有什么具体的作用呢,不加的话会对我们的结果造成影响吗?

__name__

首先对于用双下划线开头且结尾的变量,在 Python 中被称为内置变量,除了 __name__,我们常见的还有 __init____dict__ 等等.那么有多少内置变量呢?我们可以通过下面在交互界面输入下面的命令,查看 Python 全部内置变量和内置函数

>>> dir(__builtins__)

结果如下图:

不同情况下的 __name__ 的值

首先我们需要知道 __name__ 在不同情况下会有不同值,它的值取决于我们是如何执行脚本的.我们可以通过几个例子感受一下:

Example 0

# test.py
print(f'__name__ 在 test.py 值为 {__name__}')

然后直接执行一下代码

$ python test.py

然后看一下输出

$ python test.py
__name__ 在 test.py 值为 __main__

在这个例子中,我们发现 __name__ 的值是 __main__

Example 1

在这个例子中,我们重新创建一个脚本 test1.py 然后我们在 test1.py 中调用 test.py

# test1.py
import test
print(f'__name__ 在 test1.py 值为 {__name__}')

接着执行一下 test1.py,再看一下输出

python test1.py
__name__ 在 test.py 值为 test
__name__ 在 test1.py 值为 __main__

结果是不是很有意思?整个过程是什么样子的呢?简单的画了一个图

什么时候使用 __name__

有时候,我们用 Python 写了一个脚本,当我们既希望这个脚本可以单独运行,同样希望它可以在其他的脚本中发挥作用. 这个时候就需要考虑使用 __name__ 了. 这里通过改造上面 Example 1的例子来直观感受一下

修改一下 test.py 文件

# test.py
def hello(name):print(f'Hello,{name}')if __name__ == '__main__':hello("test")

再修改一下 test1.py 文件

# test1.py
from test import hello
hello("test1")

然后让我们先尝试直接运行一下 test.py,很显然这个时候, if 语句条件满足,会输出 Hello,test

$ python test.py
Hello,test

这个时候我们如果运行 test1.py,程序就会输出 Hello,test1

$ python test1.py
Hello,test1

如果我们把 if __name__ == "__main__"test.py 去掉会发生什么呢?

$ python test1.py
Hello,test
Hello,test1

Whenever the Python interpreter reads a source file, it does two things:

  • it sets a few special variables like __name__, and then
  • it executes all of the code found in the file.

Let's see how this works and how it relates to your question about the __name__ checks we always see in Python scripts.

Code Sample

Let's use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called foo.py.

# Suppose this is foo.py.print("before import")
import mathprint("before functionA")
def functionA():print("Function A")print("before functionB")
def functionB():print("Function B {}".format(math.sqrt(100)))print("before __name__ guard")
if __name__ == '__main__':functionA()functionB()
print("after __name__ guard")

Special Variables

When the Python interpeter reads a source file, it first defines a few special variables. In this case, we care about the __name__ variable.

When Your Module Is the Main Program

If you are running your module (the source file) as the main program, e.g.

python foo.py

the interpreter will assign the hard-coded string "__main__" to the __name__ variable, i.e.

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__"

When Your Module Is Imported By Another

On the other hand, suppose some other module is the main program and it imports your module. This means there's a statement like this in the main program, or in some other module the main program imports:

# Suppose this is in some other main program.
import foo

The interpreter will search for your foo.py file (along with searching for a few other variants), and prior to executing that module, it will assign the name "foo" from the import statement to the __name__ variable, i.e.

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"

if __name__ == __main__:什么意思_【Python】__name__ 是什么?相关推荐

  1. if __name__ == __main__:什么意思_好冷的Python if __name__==__main__是啥东东

    在看Python标准库文件或他人写的Python模块时,经常看到py文件最后有这样一段代码: if __name__=='__main__': 'do something' 从代码字面含义理解,如果_ ...

  2. if __name__ == __main__:什么意思_秒懂Python编程中的if __name__ == 'main' 的作用和原理...

    来源:菜鸟分析 链接: https://zhuanlan.zhihu.com/p/34112508 一天偶然发现知乎上有篇关于对python编程中的if __name__ == 'main'的理解陈述 ...

  3. if函数python作用_if __name__== __main__ 的意思(作用)python代码复用

    模块是对象,并且所有的模块都有一个内置属性 __name__.一个模块的 __name__ 的值取决于您如何应用模块.如果 import 一个模块,那么模块__name__ 的值通常为模块文件名,不带 ...

  4. Python中if __name__ == ‘__main__‘:的作用和原理(自用笔记)

    if __name__ == ' __main__':的作用 一个python文件通常有两种使用方法,第一是作为脚本直接执行,第二是 import 到其他的 python 脚本中被调用(模块重用)执行 ...

  5. Python 中的 if __name__ == '__main__' 该如何理解

    程序入口 对于很多编程语言来说,程序都必须要有一个入口,比如 C,C++,以及完全面向对象的编程语言 Java,C# 等.如果你接触过这些语言,对于程序入口这个概念应该很好理解,C 和 C++ 都需要 ...

  6. 如果__name__ =='__main__':在Python中怎么办?

    In order to understand the details of __name__ variable and the if condition, let us go through a si ...

  7. python if name main 的作用_Python中if __name__ == '__main__':的作用和原理

    if __name__ == '__main__':的作用 一个python文件通常有两种使用方法,第一是作为脚本直接执行,第二是 import 到其他的 python 脚本中被调用(模块重用)执行. ...

  8. python中 if __name__ == ‘__main__‘

    很多新手刚开始学习python的时候经常会看到python 中__name__ = \'__main__\' 这样的代码,可能很多新手一开始学习的时候都比较疑惑,python 中__name__ = ...

  9. Python中if __name__=='__main__': 理解与总结(看这篇就够了,一文扫清疑惑!)

    前言 在Python当中,如果代码写得规范一些,通常会写上一句if '__name__'=='__main__:'作为程序的入口,但似乎没有这么一句代码,程序也能正常运行.这句代码多余吗?原理又在哪里 ...

最新文章

  1. Sprint会议记录(第五组)
  2. Web 四种常见的POST提交数据方式
  3. 2019牛客暑期多校训练营(第三场)J - LRU management (模拟+list+unorder_map)
  4. webx学习(三)——Webx Turbine
  5. Android P(3)---Android P版本刘海屏适配指南
  6. jstack查看某个进程堆栈信息
  7. SpringMVC读取资源文件的几种方式
  8. Android中背景透明的Dialog
  9. 手模手教你装 文能黑苹果,武可3A游戏大作的2400块主机
  10. Qt Creator 使用教程
  11. PHP+MYSQL+SCWS 做自己的站内搜索引擎
  12. 完全激活office2007
  13. java 设计模式:软件设计原则、面向对象理论、23 种设计模式
  14. M480 EMAC驱动02-IP101G测试
  15. 杨亮词汇5500-课程导学
  16. 计算机网络mac地址作用是什么,mac地址的作用是什么
  17. 做软件测试工程师真的很容易吗
  18. 主成分分析法概述、案例实例分析
  19. 生化危机 (20 分)
  20. AdaDepth: Unsupervised Content Congruent Adaptation for Depth Estimation

热门文章

  1. jquery删除替换元素remove、detach、empty、replaceWith、replaceAll
  2. tf.one_hot()
  3. codeblocks修改MINGW位置使它能编译Build
  4. dspic flash不够后,选择优化等级
  5. proteus实现单片机的仿真
  6. 处理百万级以上的数据处理
  7. 怎样设置HTML上传控件,上传文件的大小
  8. [转载] Python 天气 简单 数据分析及可视化
  9. [转载] Python—urllib模块
  10. [转载] Java中的strictfp关键字