首页 > 其他 > 详细

装饰器

时间:2019-08-23 22:13:55      阅读:84      评论:0      收藏:0      [点我收藏+]

装饰器

开放关闭原则

  1. 代码扩展进行开放
  2. 修改源代码是封闭
  3. 在不修改源代码以及调用方式,对功能额外添加的就是开放封闭原则

不用装饰器会代码冗余

# 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)

装饰器

原文:https://www.cnblogs.com/python25/p/11402561.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!