装饰器
开放关闭原则
- 代码扩展进行开放
- 修改源代码是封闭
- 在不修改源代码以及调用方式,对功能额外添加的就是开放封闭原则
不用装饰器会代码冗余
# import time
# def cen1():
# time.sleep(2)
# print("你好1")
# def cen2():
# print("你好2")
# def cen3():
# print("你好3")
# time_start=time.time()
# cen1()
# print(time.time()-time_start)
#
# time_start=time.time()
# cen2()
# print(time.time()-time_start)
不太完美的装饰器
# import time
# def cen1():
# time.sleep(2)
# print("你好1")
# def cen2():
# print("你好2")
# def cen3():
# print("你好3")
#
# def func():
# def foo(f):
# time_start=time.time()
# f()
# print(time.time()-time_start)
# return foo
# f=cen1
# cen1=func()
# cen1(f)
第一版装饰器
# import time
# def cen1():
# time.sleep(2)
# print("你好1")
# def cen2():
# print("你好2")
# def cen3():
# print("你好3")
#
# def func(f):
# def foo():
# time_start=time.time()
# f()
# print(time.time()-time_start)
# return foo
# cen1=func(cen1)
# cen1()
语法糖
# import time
# def func(f):
# def foo():
# time_start=time.time()
# f()
# print(time.time()-time_start)
# return foo
# @func#省略了把被修饰函数的地址传递给修饰器和将修饰器内的函数地址返回给被修饰的函数的名
# def cen1():
# time.sleep(2)
# print("你好1")
# cen1()
这是完美的
# def func(f):
# def foo(*args,**kwargs):
# print("修饰前的函数")
# ret=f(*args,**kwargs)
# print("修饰后的函数")
# return ret
# return foo
# @func
# def cen(*args,**kwargs):
# print(f"被修饰的函数{args,kwargs}")
# return "我是cen函数"
# print(cen(1,2,3,a=1))
这是终结规则
# 1.装饰器
# 开发封闭原则:
# 1.对扩展开放
# 2.对修改源代码及调用方式封闭
# 装饰器:不修改源代码及原调用方式的前提下,额外增加新功能
# 语法糖:写在被装饰的函数正上方
# 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)