一、函数
1.定义函数以及参数(形参、实参)
2.求最大值、求和
3.递归函数
二、生成式
列表生成式 [ ]
集合生成式 { }
字典生成式 { }
什么场景使用/改写生成式
三、生成器
四、装饰器
1.装饰器
2.如何去使用装饰器?@装饰器的名称
2. 如何去使用装饰器?@装饰器的名称
# @timeit的工作原理: download_music=timeit(download_music)
# 执行的过程:
# 1). timeit(download_music)函数的返回值是wrapper函数名.
# 2). download_music=timeit(download_music), 让download_music=wrapper
# 3). 最后一行download_music(),实质上执行的函数wrapper()
# 4). 执行wrapper函数时, f()实质上执行的函数download_music()
@timeit
def download_music():
url = "http://。。。。。。。。。。。。。。ca9b831350d8.mp3"
# 模拟浏览器访问mp3的网址,获取服务器端给我们的响应(response)
response = requests.get(url)
# 获取mp3音乐的内容
# music_content = response.content
# 打开文件,存储音乐的内容到文件中
with open("再见.mp3", 'wb') as f:
f.write(response.content)
print("再见.mp3下载完成.......")
3.基于装饰器计算下载歌曲的时间
import time
import requests
#1装饰器计算时间
def timeit(f):
def wrapper():
start = time.time()
result = f()
end = time.time()
print("%s used time is %.3fs" %(f.__name__, end-start))
return result
return wrapper
#2下载歌曲并使用装饰器
@timeit
def download_music():
url = "http://m10.music.126.net/20200719111612/e36c0e235dbad219e9d8f0e65fa62007/ymusic/0201/7233/bea2/2cb43c8bcaa7797d32e5ca9b831350d8.mp3"
response = requests.get(url)
with open("再见.mp3", 'wb') as f:
f.write(response.content)
print("再见.mp3下载完成.......")
download_music()
~
4.多个装饰器器、调用帮助的问题
import time
from functools import wraps
def welcome(f):
@wraps(f)
def wrapper(*args, **kwargs):
print("welcome..........")
result = f(*args, **kwargs)
return result
return wrapper
def logger(f):
# 这里是可变参数和关键字参数
# wraps装饰器用来保留f函数原有的属性,包括他的帮助信息
@wraps(f)
def wrapper(*args, **kwargs):
"""
wrapper function
"""
start = time.time()
# 这里是解包
result = f(*args, **kwargs)
end = time.time()
print("Logger: %s %s run %.3f s" %(time.ctime(), f.__name__, end-start))
return result
return wrapper
# 多个装饰器装饰的时候, 从下向上进行装饰的, 执行的时候是从上到下进行执行.
@welcome
@logger # add = logger(add)====> add=wrapper
def add(num1, num2):
"""
add function
"""
time.sleep(0.1)
return num1 + num2
result = add(10, 20)
print(result)
# 装饰器: 用来装饰函数或者类的工具, 在不改变源代码的情况下给函数/类添加额外功能.
# 装饰器装饰的是函数/类,所以需要传递的参数是函数名或者类名。
import time # 时间处理模块
# HTTP请求库,多用于网络爬虫, 需要pip install 下载的
import requests
@timeit
def add(num1, num2):
time.sleep(0.2)
return num1 + num2
# download_music()
"""
分析add函数执行的过程:
1. add(10, 20)调用函数
2. 发现add函数被装饰器timeit装饰了, @timeit==> add=timeit(add)
3. timeit(add)函数的返回值是wrapper函数, add=timeit(add)这里add=wrapper
4. 终于知道add函数是什么了.add(10, 20)===> wrapper(10, 20)
5. 在wrapper函数中有f()===> add(10, 20)
6. 返回f()函数的返回值30
"""
print(add(10, 20))