Python-18-模块和包

模块和包

一、模块

在Python中,以.py为扩展名的文件就是一个模块(module)。Python模块中可以写入正常的Python代码。

模块名,文件的基本名就是模块名。比如:test.py的模块名是test

将项目的不同功能拆分,分配到多个开发人员,不同人员根据接口文档进行开发,这个过程可以看作模块化

1. 导入模块

1.1 import 模块名
  • 语法
import 模块1
import 模块1, 模块2....
  • 代码
import time, math

# 模块中功能引用的调用
# 模块.功能引用名
print(time.time())
print(math.pi)
1.2 from … import …
  • 语法
from 模块 import 功能引用名
from 模块 import 引用1, 引用2
  • 代码
from time import time, sleep

# 模块中功能引用的调用
# 模块.功能引用名
print(time())
sleep(2)
print(time())

print(localtime())			# 没有导入localtime函数,则不能使用
1.3 from…import *
# 使用 * 导入模块中的所有引用
from time import *

# 模块中功能引用的调用
# 模块.功能引用名
print(time())
sleep(2)
print(time())

print(localtime())
1.4 as别名
  • 语法
import 模块 as 模块的别名    # 别名建议全部使用大写
from 模块 import 引用 as 引用的别名
  • 代码
# 第一种
import time as TM		# 起别名之后,之前的名称不能使用

print(time.time())		# NameError: name 'time' is not defined
print(TM.time())


# 第二种
from time import time as TIME

print(time())			# NameError: name 'time' is not defined
print(TIME())

2. 制作模块

2.1 定义模块

定义模块就是创建一个.py的文件,这个文件的基本名必须满足标识符命名规则。

# test_01.py

def func1(a, b):
    """ 求和函数 """
    print(a + b)
2.2 测试模块

当开发人员开发完一个模块后要进行自测,需要在自身模块中执行代码。

# test.py

def func1(a, b):
    print(a + b)
func1(2, 3)

# 主模块
import test
test.func1(3, 5)

""" 输出结果:
5
8
"""

但是当test.py作为导入模块时,在主模块中会执行导入模块中的代码,这个情况需要规避。

# test.py

def func1(a, b):
    print(a + b)
if __name__ == '__main__':	# 当test.py作为主模块运行时,内置变量__name__的值为__main__
	func1(2, 3)
    
# 主模块
import test
print(test.__name__)	# test。当test作为导入模块时,在主模块中,test的内置变量__name__值为模块名test
test.func1(2, 5)				# 5
2.3 调用模块
# 第一种方式
import test

# 第二种方式
from test import func1
2.4 注意事项
# 不同模块中有相同的引用名,后面的会覆盖前面
from time import time
from test import time

3. __all__列表

当使用from ... import *导入模块的引用时,只能导入__all__中定义的引用。

# test.py

__all__ = ['func1']

def func1():
    print('函数func1')

def func2():
    print('函数func2')

    
# 主模块
from test import *

func1()
func2()			# 报错。由于func2在__all__列表中未定义

二、包

当目录中包含一个文件__init__.py时,这个目录就叫做Python的,目录的名字叫做包名。

包中的模块的模块名为:包名.模块名

2.1 定义包

"""
|-- test57			# 包。包名为 test57
  |-- __init__.py	# 模块名:test57
  |-- module_01.py	# test57.module_01
  |-- module_02.py  # test57.module_02
"""

# moduel_01.py
def func1():
    print('moduel_01')
    
# module_02.py
def func1():
    print('moduel_02')
    
# 主模块
# 使用5种导入格式

2.2 导入包

  1. import 包名.模块名
  2. from 包名 import 模块名
  3. from 包名 import * # 星号表示模块,如果未定义all列表则不能导入任何模块。
  4. from 包名.模块 import *
  5. from 包名.模块 import 功能引用名(函数、变量、类名)

2.3 all列表

__all__需要定义在__init__.py文件中;

如果未定义,当使用from 包 import *时,不能导入模块;

__all__必须定义。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值