Maison  >  Article  >  développement back-end  >  关于python中__ name__值的测试详细介绍

关于python中__ name__值的测试详细介绍

高洛峰
高洛峰original
2017-03-19 14:01:481665parcourir

这篇文章主要介绍关于python中__ name__值的测试详细介绍

测试中用到的代码如下:

#test_name0.py
def test():
    return name

print name
print test()
import test_name1
test_name1.test()
#test_name1.py
def test():
    print name
    
print name

python顶层解释器中执行命令与结果如下:

In [1]: type(name)
Out[1]: str
In [2]: print name
Out[2]: main
In [3]: import test_name0
test_name0
test_name0
test_name1
test_name1

在cmd中执行python test_name0.py,结果如下:

main
main
test_name1
test_name1

由此可以看出:

(1)在python顶层解释器或直接运行的脚本中name=='main'

(2)在调用的模块中name==<a href="http://www.php.cn/code/8212.html" target="_blank">module</a> name

(3)发现一个非预期的情况,就是在运行了test_name0.py的脚本后再import test_name0,或者import test_name0后再运行test_name0.py的脚本,得到的结果是

test_name0
test_name0
test_name1

main
main
test_name1

而不是

test_name0
test_name0
test_name1
test_name1

main
main
test_name1
test_name1

将问题的关键整理后在segmentfault上提问,了解了出现此问题的原因。
即:python模块有缓存,import一次后再import,模块顶级作用域的代码不会再执行。

(4)test_name0和test_name1两个模块中的test函数是同名的,这并不会有没有什么问题,因为模块名不同而可以区分这两个test函数,但要避免模块的重名。

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn