最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

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

来源:动视网 责编:小采 时间:2020-11-27 14:25:21
文档

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

关于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 tes
推荐度:
导读关于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 tes


这篇文章主要介绍关于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__值的测试详细介绍

关于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 tes
推荐度:
标签: 中的 介绍 里面
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top