PHP前端开发

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

百变鹏仔 3小时前 #Python
文章标签 详细介绍

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

测试中用到的代码如下:

#test_name0.pydef test():    return nameprint nameprint test()import test_name1test_name1.test()
#test_name1.pydef test():    print name    print name

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

In [1]: type(name)Out[1]: strIn [2]: print nameOut[2]: mainIn [3]: import test_name0test_name0test_name0test_name1test_name1

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

mainmaintest_name1test_name1

由此可以看出:

立即学习“Python免费学习笔记(深入)”;

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

(2)在调用的模块中name==module name

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

test_name0test_name0test_name1

mainmaintest_name1

而不是

test_name0test_name0test_name1test_name1

mainmaintest_name1test_name1

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

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