文件夹转换为自定义包的方法及一些坑;__init__

本文详细介绍了如何创建和导入自定义Python包,探讨了避免包名与模块名冲突的方法,以及与导入第三方包如PyTorch模块的区别。通过实例演示了正确的导入方式,帮助读者理解Python包管理的常见陷阱和最佳实践。
摘要由CSDN通过智能技术生成

一、创建一个自定义包

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模块

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZGPing@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值