我们在实际开发中,可能需要应用到多个模块,使用模块可以有效避免变量名或函数名重名引发的冲突,为了方便管理,python为我们提供了包的概念。
什么是包呢?简单理解,包就是目录,只不过在该目录下必须存在一个名为“init.py” 的文件。
注意,这是 Python 2.x 的规定,而在 Python 3.x 中,init.py 对包来说,并不是必须的。
一:创建包
如下图所示:
二:init.py文件
就如上边所说,python3包中__init__.py文件不是必须的。但是有也是没有问题的。
对于__init__.py文件来说,首先是一个python文件,所有还可以用来写python模块,但是不建议这么写,尽量保证__init__.py足够轻:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/12/30 15:02
# @Author : camellia
# @Email : 805795955@qq.com
# @File : __init__.py.py
# @Software: PyCharm
class CLanguage:
def __init__(self, name, add):
self.name = name
self.add = add
def say(self):
print(self.name, self.add)
这样,我们可以直接在代码中调用CLanguage这个类。但是 不建议这么写。
init.py还有一个作用就是模糊导入,模糊导入中的*中的模块是由__all__来定义的,init.py的另外一个作用就是定义package中的__all__,用来模糊导入,这个在下边的迷糊导入会说到
三:导入包
我们在包下边创建两个python模块:
test1.py:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2022/1/6 15:39
# @Author : stone
# @Email : 805795955@qq.com
# @File : test1.py
# @Software: PyCharm
def plus():
print("1 + 1 = 2")
test2.py:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2022/1/6 15:39
# @Author : stone
# @Email : 805795955@qq.com
# @File : test2.py
# @Software: PyCharm
def reduces():
print("1 - 1 = 0")
导入包这里和导入模块是差不多的。
但是这里分为
1:精确导入
(1):导入包(这样导入只能使用__init__.py中的内容)
import testPackage
# 调用__init__.py中的方法
CLanguage = testPackage.CLanguage('时间里的', 'https://guanchao.site')
CLanguage.say()
输出:
时间里的 https://guanchao.site
(2):精确导入 导入某一个模块
import testPackage.test2
testPackage.test2.reduces()
输出:
1 - 1 = 0
(3):精确导入(导入某一个包下某一个模块下的某一个方法)
from testPackage.test1 import plus
# 调用方法
plus()
输出:
1 + 1 = 2
2:模糊导入
在__init__.py中 添加如下代码:
__all__ = ["test1", "test2"]
在文件中调用:
# 模糊导入
from testPackage import *
# 调用方法
test1.plus()
test2.reduces()
输出:
1 + 1 = 2
1 - 1 = 0
四:查看模块成员:dir()函数
使用dir函数:
# 导入包(这样导入只能使用__init__.py中的内容)
import testPackage
print(dir(testPackage))
输出:
['CLanguage', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
五:查看模块成员:__all__变量
import testPackage
print(testPackage.__all__)
输出:
['test1', 'test2']
六:__file__属性:查看模块的源文件路径
import testPackage
print(testPackage.__file__)
import testPackage.test2
print(testPackage.test2.__file__)
输出:
F:\camellia\python\testProject\testPackage__init__.py
F:\camellia\python\testProject\testPackage\test2.py
以上大概就是python中的包的使用方法
有好的建议,请在下方输入你的评论。