python模块导入问题和if __name__ == '__main__'语句的使用

1. 导入模块时,如果导入的新模块不在当前模块所在同一路径下,那么直接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__:”后面的语句就没有被执行。




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值