一、创建一个自定义包
1.定义:包其实就是文件夹,更确切的说,是一个包含“init.py”文件的文件夹。init.py文件一般是空的。
2.如图各文件内容
注:当添加“ __init __ .py”文件后文件夹里面有个点。
二、导入该自定义包
1.定义:导入方法可归结为以下4种,实际上可用的就后面3种。对于第三方包的话将下面的包名、模块名、成员名依次往前替换,那么前三种就是导入第三方包的模块的三种方法。
import 包名 [as 别名] #在这里用不了,会出错
import 包名.模块名 [as 别名] #使用模块中的成员(可以是变量、函数或类)时,前缀既需要包名也需要模块名
from 包名 import 模块名 [as 别名] #使用模块中的成员(可以是变量、函数或类)时前缀不需要带包名,但需要带模块名。
from 包名.模块名 import 成员名 [as 别名] #导入的“包.模块”中的成员名(可以是变量、函数或类)。通过该方式导入的变量(函数、类),在使用时可以直接使用变量名(函数名、类名)调用,不需要前缀。
注: [] 括起来的部分,是可选部分
2.实验代码
2-1.import 包名 [as 别名]
import test1 #光有包会出错,最少要导入到模块
test1.hello.print_h()
[out]
执行__init__文件
Traceback (most recent call last):
File "D:/pycharm/test/main1.py", line 4, in <module>
test1.hello.print_h()
AttributeError: module 'test1' has no attribute 'hello'
2-2.import 包名.模块名 [as 别名]
import test1.hello
test1.hello.print_h()
[out]
执行__init__文件
hello
2-3.from 包名 import 模块名 [as 别名]
from test1 import hello
hello.print_h()
[out]
执行__init__文件 #∵运行了__init__文件
hello
2-4.from 包名.模块名 import 成员名 [as 别名]
from test1.hello import print_h
print_h()
[out]
执行__init__文件 #∵运行了__init__文件
hello
注:import test1 、import test1.hello、from test1 import hello、from test1.hello import print_h都会先执行__init__文件里的代码,所以一般__init__文件里面没有代码。
三、遇到过的坑
1.当包名和该包的一个模块名相同时会出现错误
[out]
Traceback (most recent call last):
File "D:/pycharm/test/test1/test1.py", line 1, in <module>
from test1.hello import print_h
File "D:\pycharm\test\test1\test1.py", line 1, in <module>
from test1.hello import print_h
ModuleNotFoundError: No module named 'test1.hello'; 'test1' is not a package
方法1:避免名字相同。
方法2:把test1删去,用from hello import print_h。应该是因为这两个.py文件是同一路径下。
最好用方法1,方法2试过,可能会遇到其他问题。
四、与导入第三方包中的模块比较(如pytorch包)
其实pytorch包一般是提前安装在环境中了,程序里一般是用
上面提到的三种方法,并不会用到包名。pytorch包最主要的的模块有:
1.torch模块
2.torch.Tensor模块
3.torch.sparse模块
4.torch.cuda模块
5.torch.nn模块
6.torch.nn.functional函数模块
7.torch.nn.init模块
8.torch.optim模块
9.torch.autograd模块
10.torch.distributed模块
11.torch.distributions模块
12.torch.hub模块
13.torch.jit模块
14.torch.multiprocessing模块
15.torch.random模块
16.torch.onnx模块