好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

这篇文章主要介绍关于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==module 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函数,但要避免模块的重名。

以上就是关于python中__ name__值的测试详细介绍的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于关于python中__name__值的测试详细介绍的详细内容...

  阅读:49次