Python装饰器
1、先明白这段代码
def foo():
print('foo')
foo # 表示是函数
foo() # 表示执行foo函数
def foo():
print('foo')
foo = lambda x: x + 1
foo() # 执行lambda表达式,而不再是原来的foo函数,因为foo这个名字被重新指向了另外一个匿名函数
函数名仅仅是个变量,只不过指向了定义的函数而已,所以才能通过 函数名()调用,如果 函数名=xxx被修改了,那么当在执行 函数名()时,调用的就不知之前的那个函数了
写代码要遵循开放封闭原则,虽然在这个原则是用的面向对象开发,但是也适用于函数式编程,简单来说,它规定已经实现的功能代码不允许被修改,但可以被扩展,即:
- 封闭:已实现的功能代码块
- 开放:对扩展开发
2. 装饰器
# 定义函数:完成包裹数据
def makeBold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
# 定义函数:完成包裹数据
def makeItalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makeBold
def test1():
return "hello world-1"
@makeItalic
def test2():
return "hello world-2"
@makeBold
@makeItalic
def test3():
return "hello world-3"
print(test1()) # <b>hello world-1</b>
print(test2()) # <i>hello world-2</i>
print(test3()) # <b><i>hello world-3</i></b>
3. 装饰器(decorator)功能
- 引入日志
- 函数执行时间统计
- 执行函数前预备处理
- 执行函数后清理功能
- 权限校验等场景
- 缓存
4. 装饰器示例
例1:无参数的函数
装饰器理解:
1. 把被装饰的函数当做参数传递进去
2. 装饰函数返回值是一个函数,这个函数是在外面被执行的,就是返回值加()
3. 被装饰函数在内层函数被执行
from time import ctime, sleep
def timefun(func):
def wrapped_func():
print("%s called at %s" % (func.__name__, ctime()))
func()
return wrapped_func
@timefun
def foo():
print("I am foo")
foo()
sleep(2)
foo()
#上面代码理解装饰器执行行为可理解成
foo = timefun(foo)
# foo先作为参数赋值给func后,foo接收指向timefun返回的wrapped_func
foo()
# 调用foo(),即等价调用wrapped_func()
# 内部函数wrapped_func被引用,所以外部函数的func变量(自由变量)并没有释放
# func里保存的是原foo函数对象
例2:被装饰的函数有参数
from time import ctime, sleep
def timefun(func):
def wrapped_func(a, b):
print("%s called at %s" % (func.__name__, ctime()))
print(a, b)
func(a, b)
return wrapped_func
@timefun
def foo(a, b):
print(a+b)
foo(3,5)
sleep(2)
foo(2,4)
例3:被装饰的函数有不定长参数
from time import ctime, sleep
def timefun(func):
def wrapped_func(*args, **kwargs):
print("--%s--%s"%(func.__name__, ctime()))
func(*args, **kwargs)
return wrapped_func
@timefun # 相当于foo = timefun(foo) # foo相当于外部函数的返回值
# foo(3,5,7),相当于执行内部函数
def foo(a, b, c):
print(a+b+c)
foo(3,5,7)
例4:装饰器中的return
from time import ctime, sleep
def timefun(func):
def wrapped_func():
print("--%s--%s" % (func.__name__, ctime()))
func()
return wrapped_func
@timefun
def foo():
print("I am foo")
@timefun
def getInfo():
return '----hahaha---'
foo() # --foo--Sun Dec 29 00:39:58 2019
# I am foo
sleep(2)
foo() # --foo--Sun Dec 29 00:40:00 2019
# I am foo
print(getInfo()) # --getInfo--Sun Dec 29 00:43:06 2019
# None
func()前加上return
from time import ctime, sleep
def timefun(func):
def wrapped_func():
print("--%s--%s" % (func.__name__, ctime()))
return func() # 加上return
return wrapped_func
@timefun
def foo():
print("I am foo")
@timefun
def getInfo():
return '----hahaha---'
foo() # --foo--Sun Dec 29 00:39:58 2019
# I am foo
sleep(2)
foo() # --foo--Sun Dec 29 00:40:00 2019
# I am foo
print(getInfo()) # --getInfo--Sun Dec 29 00:43:06 2019
# ----hahaha---
总结:
- 一般情况下为了让装饰器更通用,可以有return
例5:装饰器带参数,在原有装饰器的基础上,设置外部变量
from time import ctime, sleep
def timefun_arg(pre="hello"):
def timefun(func):
def wrapped_func():
print("--%s--%s--%s" % (func.__name__, ctime(), pre))
return func()
return wrapped_func
return timefun
@timefun_arg("itcast") # foo = timefun_arg("参数")(foo) # timefun_arg("参数")返回第一层函数的 返回值1
# 返回值1(foo) # 执行第二层函数,把函数引用传进去 # 返回值2
# 返回值2() # 等于外面写的foo() # 执行真正被装饰的函数
def foo():
print("I am foo")
foo() # --foo--Sun Dec 29 01:00:01 2019--itcast
# I am foo
# 可以理解为
#foo()==timefun_arg("itcast")(foo)()
例6:类装饰器(扩展,非重点)
装饰器函数其实是这样一个接口约束,它必须接受一个callable对象作为参数,然后返回一个callable对象。在Python中一般callable对象都是函数,但也有例外。只要某个对象重写了 __call__() 方法,那么这个对象就是callable的。
# class Test():
# def __call__(self):
# print('call me!')
#
# t = Test()
# t() # call me
# 类装饰器demo
class Test(object):
def __init__(self, func):
print("---初始化---")
print("func name is %s"%func.__name__)
self.__func = func
def __call__(self):
print("---装饰器中的功能---")
self.__func()
#说明:
#1. 当用Test来装作装饰器对test函数进行装饰的时候,首先会创建Test的实例对象
# 并且会把test这个函数名当做参数传递到__init__方法中
# 即在__init__方法中的属性__func指向了test指向的函数
#2. test指向了用Test创建出来的实例对象
#3. 当在使用test()进行调用时,就相当于让这个对象(),因此会调用这个对象的__call__方法
#4. 为了能够在__call__方法中调用原来test指向的函数体,所以在__init__方法中就需要一个实例属性来保存这个函数体的引用
# 所以才有了self.__func = func这句代码,从而在调用__call__方法中能够调用到test之前的函数体
@Test
def test():
print("----test---")
test()
# ---初始化---
# func name is test
# ---装饰器中的功能---
# ----test---

浙公网安备 33010602011771号