开放封闭原则:
对扩展开放
对修改源代码和调用方式是封闭
装饰器:
# def warpper(f):
# def inner(*args,**kwargs):
# print("被装饰函数执行前")
# ret = f(*args,**kwargs)
# print("被装饰函数执行后")
# return ret
# return inner
#
# @warpper
# def func(*args,**kwargs):
# print(f"被装饰的{args,kwargs}")
# return "我是func函数"
# print(func(1,2,3,4,5,6,7,8,a=1))
# def warpper(f):
# def inner(*args,**kwargs):
# f(*args,**kwargs)
# return inner
#
# @warpper
# def func():
# print(111)
1. 标准版装饰器:
# def func(f):
# def foo(*args,**kwargs):
# ret = f(*args,**kwargs)
# print("被装饰之后")
# return ret
# return foo
#
# @func
# def func1(*args,**kwargs):
# print("被装饰函数")
# return args,kwargs
# print(func1(1,2,3))
标准装饰器拆解:
import time
def warpper(f):
def inner(*args,**kwargs):
print("被装饰函数执行前")
ret = f(*args,**kwargs)
print("被装饰函数后")
return ret
return inner
def func(*args,**kwargs):
print(f"被装饰的{args,kwargs}")
return "我是fubnc函数"
func = warpper(func)
print(func(1,2,3,4,5,6,a = 1))
语法糖:写在被装饰函数的正上方
语法糖和被装饰的函数之间可以有空行但是不建议这样写
装饰器一定要写在被装饰函数的前面
2. 带参数的装饰器:
有参: 在标准装饰器的外层,套了一层,多套一层就需要额外的调用一层
语法糖:@auth(参数)
有参装饰器:
def warpper(func):
def inner(*args,**kwargs):
user = input("user:")
pwd = input("pwd:")
if user == 'alex' and pwd == "dsb":
func(*args,**kwargs)
return inner
@warpper
def foo():
print("被装饰的函数")
foo()
3. 多个装饰器装饰一个:
多个装饰器装饰一个函数的时候,先执行离被装饰函数最近的装饰器
# def auth(func): # wrapper1装饰器里的 inner
# def inner(*args,**kwargs):
# print(123)
# func(*args,**kwargs)
# print(321)
# return inner
#
#
# def wrapper1(func): # warpper2装饰器里的 inner
# def inner(*args,**kwargs):
# print(111)
# func(*args,**kwargs)
# return inner
#
#
# def wrapper2(func): # 被装饰的函数foo
# def inner(*args,**kwargs):
# print(222)
# func(*args,**kwargs)
# print(567)
# return inner
#
#
# @auth
# @wrapper1
# @wrapper2
# def foo():
# print("www.baidu.com")
# foo()
# import time
# time.time() #时间戳 -- 浮点数
# time.sleep(1) # 秒 -- 睡眠 -- 阻塞
# 7 -- 1
# 3 -- 0.5
# 4 -- 0.5
# 6 -- 0.3