day14-装饰器和模块(10.8)
知识大纲:
1、装饰器
2、模块(模块和包的导入,系统模块的使用)
3、模块:math,random,time\datetime-(时间管理)非常重要,OS-(文件和文件加的管理)重要,os.path()模块
4、hashlib - 了解
1、给函数添加功能
装饰器的作用:给已经写好的函数新增功能
- 给函数新增功能方案一:直接修改原函数,把新增的功能加进去
存在的问题:如果多个函数都需要新增相同的功能,相同功能的代码需要写多遍
import time
from random import randint
def download(name):
start = time.time()
print(f'{name}开始下载')
time.sleep(randint(1, 3))
print(f'{name}下载结束')
end = time.time()
print(f'总时间:{end-start}s')
def func1():
start = time.time()
num1 = float(input('请输入数字1:'))
num2 = float(input('请输入数字2:'))
print(f'{num1} + {num2} = {num1 + num2}')
end = time.time()
print(f'总时间:{end - start}s')
# download('活着')
# func1()
# 需求:增加功能,(打印电影下载的时长)
# 方案二:实参高阶函数
def download2(name='电影1'):
print(f'{name}开始下载')
time.sleep(randint(1, 3))
print(f'{name}下载结束')
def func12():
num1 = float(input('请输入数字1:'))
num2 = float(input('请输入数字2:'))
print(f'{num1} + {num2} = {num1 + num2}')
def func22():
print('hello world!')
# def logo(fn):
# fn()
# print('千锋教育!')
# def total_time(fn):
# start = time.time()
# # 实现原函数的功能
# fn()
# end = time.time()
# print(f'总时间:{end - start}s')
# download2()
# func12()
# total_time(func22)
# total_time(download2)
# total_time(func12)
# total_time(func22)
# logo(func22)
# 方案三:使用装饰器**
# 装饰器 = 实参高阶函数 + 返回值高阶函数 + 糖语法
def total_time(fn):
def new_fn():
start = time.time()
fn()
end = time.time()
print(f'总时间:{end - start}s')
return new_fn
def logo(fn):
def new_fn():
fn()
print('千锋教育')
return new_fn
@logo
def download3(name='电影1'):
print(f'{name}开始下载')
time.sleep(randint(1, 3))
print(f'{name}下载结束')
@total_time
def func12():
num1 = float(input('请输入数字1:'))
num2 = float(input('请输入数字2:'))
print(f'{num1} + {num2} = {num1 + num2}')
download3()
func12()
2、装饰器语法
# 装饰器 = 实参高阶函数 + 返回值高阶函数 + 糖语法
# 1. 固定结构
"""
def 装饰器名称(旧(原)函数): # #新函数,旧函数名随意取
def 新函数(*args, **kwargs): # # 任意参数,个数,位置参数,关键字参数
result = 旧函数(*args, **kwargs)
实现新增的功能
return result
return 新函数
"""
用@使用装饰器的原理:
import time
def add_logo(fn):
def new_fn(*args, **kwargs):
result = fn(*args, **kwargs)
print('千锋教育!')
return result
return new_fn
@add_logo
def func():
print('hello world!')
@add_logo
def func1(x):
print(x * 2)
@add_logo # func2 = add_logo(func2)
def func2():
return 100
func()
func1(100)
func1(x=200)
print(func2())
# 练习1:写一个统计函数执行时间的装饰器
def total_time(fn):
def new_fn(*args, **kwargs):
start = time.time()
result = fn(*args, **kwargs)
end = time.time()
print(f'总时间:{end - start}')
return result
return new_fn
# 练习2:写一个装饰器在原函数的开头打印 start
def add_start(fn):
def new_fn(*args, **kwargs):
print('start!')
result = fn(*args, **kwargs)
return result
return new_fn
# 练习3:将返回值是数字的函数的返回值变成原来的10000倍
def blow_up(fn):
def new_fn(*args, **kwargs):
result = fn(*args, **kwargs)
if type(result) in (int, float):
return result * 10000
return result
return new_fn
3、模块的导入
- 模块
一个py文件就是一个模块
可以在一个模块中使用另外一个模块中的内容,
前提:1)被另外一个模块使用的模块的名字必须符合变量名的要求 2)被使用之前需要导入
- 导入模块(重要)
“”"
1)import 模块名 - 直接导入指定模块,导入后能通过"模块名.“的方式使用模块中所有的全局变量
2)from 模块名 import 变量名1,变量名2,变量名3,… - 通过模块导入指定变量,导入后直接使用指定的变量
3)from 模块名 import * - 通过模块导入模块中所有全局变量,导入后直接使用变量
4)重命名
import 模块名 as 新模块名 - 使用模块的时候用新模块名来使用
from 模块名 import 变量名1 as 新变量名1, 变量名2, 变量名3,…
“””
# =================导入方式1==================
# import test1
# print(test1.a)
# print(test1.x)
# test1.func1()
#
# import random
# random.randint(10, 20)
# =================导入方式2==================
# from test1 import a, func1
# print(a)
# func1()
# # print(x) # NameError: name 'x' is not defined
# =================导入方式3==================
# from test1 import *
# print(a)
# print(x)
# func1()
# =================导入方式4==================
# import test1 as ts1
# # import numpy as np
# # import pandas as pd
#
# test1 = 'hello'
#
# print(test1, ts1.a)
# ts1.func1()
from test1 import x as t_x, a
x = '小明'
print(x, t_x)
print(a)
4、导入模块的原理
- 原理
“”"
当代码执行到导入模块的时候,系统会自动进入该模块将模块中所有的代码都执行一遍
“”"- 这个if语句的特点:在if语句中的代码当前模块被别的模块导入的时候不会执行;如果直接运行当前模块又会执行
from download_file import download_film
print(f'04:{__name__}')
download_film('这个杀手不太冷')
# 这个if语句的特点:在if语句中的代码当前模块被别的模块导入的时候不会执行;如果直接运行当前模块又会执行
if __name__ == '__main__':
pass
5、包的导入
# 1. 导入包中的模块(重要)
"""
1) import 包名 - 要修改__init__.py文件才有意义,否则无用
2) import 包名.模块名
3) from 包名 import 模块名1, 模块名2,...
4) from 包名.模块名 import 变量1, 变量2,...
"""
# =============导入方式1=============
# import fileManager
# =============导入方式2=============
# a. 不重命名
# import fileManager.csvFile
# print(fileManager.csvFile.aa)
# fileManager.csvFile.read_file()
# b. 重命名
# import fileManager.csvFile as csvFile
# print(csvFile.aa)
# csvFile.read_file()
# =============导入方式3=============
# from fileManager import csvFile, jsonFile
# print(csvFile.aa)
# jsonFile.write_dict()
# =============导入方式4=============
# from fileManager.csvFile import read_file
# read_file()
2. 导入包的原理 # 导入包中的模块的内容的时候,系统会先执行包中__init__.py文件中的内容,再执行模块中的内容
# from fileManager import csvFile
# 功能一
# import fileManager
# fileManager.csvFile.read_file()
# fileManager.jsonFile.write_dict()
# 功能二
# from fileManager.jsonFile import write_dict
# from fileManager import write_dict
# write_dict()
# import fileManager
# fileManager.write_dict()
# fileManager.open_file()
from fileManager import open_file, write_dict
open_file()
6、数学模块
math - 普通数字相关的数学函数
cmath - 复数相关的数据函数普通数字(int、float): 100、-23.8、0.23
复数(complex):a+bj (a-实部、b-虚部、j是虚数单位;j**2 == -1)
x = 10 + 2j
y = 20 - 3j
print(type(x))
print(x + y) # 30 - 1j
print(x * y) # 206 + 10j
- ceil(浮点数) - 将浮点数转换成整数(向大取整)
print(math.ceil(1.9))
print(math.ceil(1.1))
- floor(浮点数) - 将浮点数转换成整数(向小取整)
print(math.floor(1.9)) # 1
print(math.floor(1.1)) # 1
- round(浮点数) - 将浮点数转换成整数(四舍五入)
print(round(1.9)) # 2
print(round(1.1)) # 1
randrange(M,N,step) - 随机整数
import random
# randrange(M,N,step) - 随机整数
print(random.randrange(10, 20, 2))
randint(M, N) - 随机整数
print(random.randint(10, 20))
random() - 产生0~1的随机小数
print(random.random()) # 0 ~ 1
print(random.random() * 10) # 0 ~ 10
print(random.random() * 9 + 1) # 1 ~ 10
choices(序列, k=数量) - 从序列中随机获取指定数量的元素(有放回抽取)
choice(序列) - 从序列中随机获取一个元素
nums = [1, 2, 3, 4, 5]
print(random.choices(nums, k=4))
sample(序列, k=数量) - 从序列中随机获取指定数量的元素(无放回抽取)
print(random.sample(nums, k=4))
shuffle(列表) - 将列表中元素的顺序随机打乱
random.shuffle(nums)
print(nums)
7、时间模块
1.获取当前时间
时间戳:以当前时间到1970年1月1日0时0分0秒(格林威治时间)的时间差来记录一个时间(时间差的单位是秒)
import time
import datetime
t1 = time.time()
print(t1)
'2021年10月8日 16:56:00'
# 1633683338.1856189
- 获取本地时间
localtime() - 获取当前的本地时间(返回值是结构体时间)
t2 = time.localtime()
print(t2, t2.tm_year)
localtime(时间戳) - 回去指定时间戳对应的本地时间
t3 = time.localtime(0)
print(t3)
t4 = time.localtime(1633683338.1856189)
print(t4)
- 睡眠 - 让程序暂停运行
sleep(时间) - 时间单位:秒
time.sleep(2)
print('==================')
4.将结构体时间转换成时间戳
mktime(结构体时间)
t5 = time.mktime(t2)
print(t5)
8、其他py文档
download_file.py def download_film(name): print(f'------------{name}开始下载------------') print('检测网络状态') print('连接服务器') print(f'传递数据:{name}') print('保存数据!') print(f'{name}下载完成!') # 这个if语句的特点:在if语句中的代码当前模块被别的模块导入的时候不会执行;如果直接运行当前模块又会执行 print(f'download_file:{__name__}') if __name__ == '__main__': download_film('加勒比海盗1') download_film('吸血鬼日记') download_film('复仇者联盟') sum1 = 1 for x in range(1, 21): sum1 *= x print(sum1)
test1.py print('test1开始执行') a = 100 for x in range(3): print(f'x:{x}') def func1(): print('test1中的函数') print('test1结束执行')
9、如何创建包
# python package 文件包 # 自带 __init__.py # directory put文件夹 # 加入 __init__.py 变成文件包
fileManager包
__init__.py
print('包中__init__被执行')
# 功能一:导入包中所有的模块,让在外部直接导入包的时候可以通过包去使用包中所有的模块
from fileManager import csvFile, jsonFile, textFile
# 功能二:建立常用方法和数据的快捷键
# write_dict = jsonFile.write_dict
from fileManager.jsonFile import write_dict # 通过导入包用函数
# 功能三:封装通用函数
def open_file():
print('打开文件')
csvFile.py
print('csvFile开始执行')
aa = 100
def read_file():
print('获取csv文件内容')
print('csvFile执行结束')
jsonFile.py
bb = 200
def write_dict():
print('将字典写入json文件中')
textFile.py
cc = 300
def del_file():
print('删除文本文件')
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eUt6iASD-1633691037563)(C:\Users\z\Desktop\tupian\10.81.png)]
ager import csvFile, jsonFile, textFile
功能二:建立常用方法和数据的快捷键
write_dict = jsonFile.write_dict
from fileManager.jsonFile import write_dict # 通过导入包用函数
功能三:封装通用函数
def open_file():
print(‘打开文件’)
```python
csvFile.py
print('csvFile开始执行')
aa = 100
def read_file():
print('获取csv文件内容')
print('csvFile执行结束')
jsonFile.py
bb = 200
def write_dict():
print('将字典写入json文件中')
textFile.py
cc = 300
def del_file():
print('删除文本文件')
[外链图片转存中…(img-eUt6iASD-1633691037563)]