Python函数06/装饰器
内容大纲
1.装饰器
1.装饰器
1.1 开放封闭原则
扩展是开放的(增加新功能)
修改源码是封闭的(修改已经实现的功能)
在不修改源码及调用方式的前提下额外增加新的功能
1.2 装饰器
用来装饰的工具
版一:
import time
starrt_time = time.time()
def func():
time.sleep(2) #睡眠 (模拟网络延时)
print("你好")
func()
print(time.time()-start_time)
# start_time = time.time()
# def foo():
# time.sleep(3) #睡眠 (模拟网络延时)
# print("我是小明,我飞的比你高")
# foo()
# print(time.time() - start_time)
版二:
def times(f):
start_time = time.time()
f()
print(time.time() - start_time)
def foo():
time.sleep(3)
print("我好")
def func():
time.sleep(1)
s = func
func = times
func(s)
版三 (初识版装饰器)
def times(f):
def inner():
start_time = time.time()
f()
print(time.time() - start_time)
return inner
def foo():
time.sleep(1)
print("大家好")
foo = times(foo)
foo()
版四 (第二版装饰器)
def wrapper():
def inner():
print(1)
return inner #切记inner后面不要加括号
def func():
print(2)
func = wrapper(func)
func()
# def wrapper(f):
# def inner():
# print(f)
# return inner # 切记不要加括号
# wrapper("alex")
# def wrapper(f):
# def inner():
# f()
# return inner # 切记不要加括号
#
# def func():
# print("这是func函数,李业还是不行")
# func = wrapper(func)
# func()
def wrapper(f):
def inner(*args,**kwargs):
f(*args,**kwargs) #func(" ")
return inner #切记不要加括号()
def func(*args,**kwargs):
print(f"haodi{args}")
func = wrapper(func)
func("nihao","wohao")
low版
import time
def wrapper(f):
def inner(*args,**kwargs):
"被装饰前"
start_time = time.time()
f(*args,**kwargs) #func()
print(time.time() - start_time)
"被装饰后"
return inner
def func(*args,**kwsrgs):
print("nihao")
time.sleep(2)
func = wrpper(func)
func("nihao","wohao")
高级
import time
def wrapper(f):
def inner(*args,**kwargs):
"被装饰前"
start_time = time.time()
f(*args,**kwargs) #func()
print(time.time() - start_time)
"被装饰后"
return inner
@wrapper #相当于 func=wrapper(func)
def func(*args,**kwsrgs):
print("nihao")
time.sleep(2)
func("nihao","wohao")
语法糖 --- 甜 @
语法糖必须放在被装饰的函数的正上方
# import time
# def wrapper(f):
# def inner(*args,**kwargs):
# "被装饰前"
# start_time = time.time()
# ret = f(*args,**kwargs) # func("alex")
# print(time.time() - start_time)
# "被装饰后"
# return ret
# return inner # 切记不要加括号
#
# @wrapper # func = wrapper(func)
# def func(*args,**kwargs):
# print(f"这是{args}函数,李业还是不行")
# time.sleep(2) #模拟网络延时
# return "alex"
# print(func())
装饰器返回值的传递
login_dic = {
"username": None,
"flag": False
}
def auth(f):
def inner(*args,**kwargs):
if login_dic["flag"]:
return f()
else:
return login()
return inner
@auth #index = auth(index)
def index():
print(f"这是{login_dic['username']}主页")
return "主页没有内容"
def login():
print("这是一个登录页面")
user = input("username:")
pwd = input("password:")
if user == "baoyuan" and pwd == "baoyuan123":
login_dic["flag"] = True
login_dic["username"] = user
return
else:
return "用户名或密码错误!"
@auth #comment = auth(comment)
def comment():
print(f"这是{login_dic['username']}评论")
while not login_dic["flag"]:
print(comment())
2.今日练习
# 1.整理今天的笔记以及课上代码,以及代码的执行流程.
#
# 2.将模拟博客园使用装饰器进行编写.
# login_dic = {
# "username": None,
# "flag": False
# }
# def auth(f):
# def inner(*args,**kwargs):
# if login_dic["flag"]:
# return f()
# else:
# return login()
# return inner
#
# @auth
# def index():
# print(f"这是{login_dic['username']}主页")
# return "主页没有内容"
#
# def login():
# print("这是一个登录页面")
# user = input("username:")
# pwd = input("password:")
# if user == "baoyuan" and pwd == "baoyuan123":
# login_dic["flag"] = True
# login_dic["username"] = user
# return "登录成功!"
# else:
# return "用户名或密码错误!"
#
# @auth
# def comment():
# return f"这是{login_dic['username']}评论"
# #
# while not login_dic["flag"]:
# if login() == "登录成功!":
# print("登陆成功!")
# print(comment())
# else:
# print(login())
#
# 3.看代码写结果:
# def wrapper(f):
# def inner(*args,**kwargs):
# print(111)
# ret = f(*args,**kwargs)
# print(222)
# return ret
# return inner
#
# def func():
# print(333)
#
# print(444)
# func()
# print(555)
# 444
# 333
# 555
#
# 4.编写装饰器, 在每次执行被装饰函数之前打印一句’每次执行被装饰函数之前都得先经过这里’.
# def wrapper(func):
# def inner():
# print("每次执行被装饰函数之前都得先经过这里")
# func()
# return inner
# @wrapper
# def func():
# print("这是被装饰的函数")
# func()
#
5.为函数写一个装饰器,把函数的返回值 + 100然后再返回。
# def wrapper(func):
# def inner():
# ret = func()
# return ret+100
# return inner
# @wrapper
# def func():
# return 7
# result = func()
# print(result)
#
6.请实现一个装饰器,通过一次调用使被装饰的函数重复执行5次。
# def wrapper(func):
# def inner():
# for i in range(5):
# func()
# return inner
# @wrapper
# def func():
# return "这是被装饰的函数"
# func()
#
# 7.请实现一个装饰器,每次调用函数时,将被装饰的函数名以及调用被装饰函数的时间节点写入文件中。
# 可用代码:
# import time
# struct_time = time.localtime()
# print(time.strftime("%Y-%m-%d %H:%M:%S", struct_time)) # 获取当前时间节点
#
# def func():
# print(func.__name__())
# 函数名通过: 函数名.__name__获取。
# import time
# def wrapper(func):
# def inner():
# struct_time = time.localtime()
# a = time.strftime("%Y-%m-%d %H:%M:%S", struct_time)
# b = func.__name__
# with open("info","a",encoding="utf-8") as f:
# f.write(f'调用时间点:{a},函数名:{b}
')
# return inner
# @wrapper
# def func():
# print("这是被装饰的函数")
# func()