• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-09) 21次浏览 已收录 0个评论

这篇文章主要介绍关于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_name0tes<div style="color:transparent">本文来源gaodai.ma#com搞##代!^码@网*</div>t_name0test_name1test_name1

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

mainmaintest_name1test_name1

由此可以看出:

(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函数,但要避免模块的重名。

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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:关于python中__ name__值的测试详细介绍

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址