python中__name__是什么意思

2,079次阅读
没有评论

python中__name__是什么意思

在Python中,一个.py文件就是一个模块,一般情况下,模块的名字就是文件名(不包括扩展名.py)。

全局变量__name__存放的就是模块的名字。

而特殊情况就是,当一个模块作为脚本执行时或者在交互式环境中,如Ipython、Python自带的shell等直接运行代码,__name__的值不再是模块名,而是__main__。__main__是顶层代码执行作用域的名字。

导入模块时,如果导入的新模块不在当前模块所在同一路径下,那么直接import会出错。解决办法有:

(1)如果当前模块和要导入的模块属于不同的包,但是包的上级路径是一样的,那么可以直接import 包名.模块名,如import myPackeg.myModule

(2)可以先将要导入的模块加入sys.path中,再import. 如下示例:导入F:\DeepLearning目录下的test1模块

>>> import test1
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import test1
ModuleNotFoundError: No module named 'test1'
>>> import sys
>>> sys.path
['', 'D:\\Program Files\\Python\\Lib\\idlelib', 'D:\\Program Files\\Python\\python36.zip', 'D:\\Program 
Files\\Python\\DLLs', 'D:\\Program Files\\Python\\lib', 'D:\\Program Files\\Python', 'D:\\Program Files\\Python\\lib\
\site-packages']
>>> sys.path.append('F:\\DeepLearning')
>>> sys.path
['', 'D:\\Program Files\\Python\\Lib\\idlelib', 'D:\\Program Files\\Python\\python36.zip', 'D:\\Program
 Files\\Python\\DLLs', 'D:\\Program Files\\Python\\lib', 'D:\\Program Files\\Python', 'D:\\Program Files\
 \Python\\lib\\site-packages', 'F:\\DeepLearning']
>>> import test1
>>>

2. if  __name__ == '__main__'语句的使用

先看tc模块和calc模块的代码

calc模块代码:

import tc
print("32摄氏度 = %.2f华氏度"%tc.c2f(32))
print("99华氏度 = %.2f摄氏度"%tc.f2c(99))

tc模块代码:

def c2f(cel):
    fah = cel * 1.8 + 32
    return fah
 
def f2c(fah):
    cel = (fah - 32) / 1.8
    return cel
 
def test():
    print("测试,0摄氏度 = %.2f华氏度"%c2f(0))
    print("测试,0华氏度 = %.2f摄氏度"%f2c(0))
 
test()

运行calc模块后:

>>> runfile('F:/DeepLearning/calc.py', wdir='F:/DeepLearning')
Reloaded modules: tc
测试,0摄氏度 = 32.00华氏度
测试,0华氏度 = -17.78摄氏度
32摄氏度 = 89.60华氏度
99华氏度 = 37.22摄氏度

将测试语句的函数test()也执行了,如果要避免直接执行test()函数,可以将tc模块中最后一句test()语句改为:

if __name__ == '__main__':
    test()

再执行就是

>>>     runfile('F:/DeepLearning/calc.py', wdir='F:/DeepLearning')
Reloaded modules: tc
32摄氏度 = 89.60华氏度
99华氏度 = 37.22摄氏度

查看__name__属性:

>>> __name__
'__main__'
>>> tc.__name__
'tc'

这是因为__name__就是标识模块的名字的一个系统变量。这里分两种情况:假如当前模块是主模块(也就是调用其他模块的模块),那么此模块名字就是__main__,通过if判断这样就可以执行“__main__:”后面的主函数内容;假如此模块是被import的,则此模块名字为文件名字(不加后面的.py),通过if判断这样就会跳过“__mian__:”后面的内容。上例中,tc.__name__不是'main',所以tc模块中的“__mian__:”后面的语句就没有被执行。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试
2

相关文章:

版权声明:wuyou2019-09-27发表,共计2387字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)