闭包、装饰器

闭包

内部函数对外部函数作用域里变量的引用(非全局变量),则称内部函数为闭包。

  • 优缺点
    1.闭包似优化了变量,原来需要类对象完成的工作,闭包也可以完成
    2.由于闭包引用了外部函数的局部变量,则外部函数的局部变量没有及时释放,消耗内存

装饰器

  • 效果
    装饰原函数,扩展原函数的功能,在原函数执行之前做一点儿事情,比如:
  1. 引入日志
  2. 函数执行时间统计
  3. 执行函数前预备处理
  4. 执行函数后清理功能
  5. 权限校验等场景
  6. 缓存
  • 原理
def w1(f):
    def inner():
        print("----验证权限----")
        f()
        # return f()
    return inner
    
def f1():
    print("----do f1----")
  
@w1
def f2():
    print("----do f2----")
    
    
f1 = w1(f1)
f1()

f2()

形如@w1,就叫装饰器,是python的一种语法糖。实际上等同于执行了f2 = w1(f2)

# 被装饰的函数无参数


from time import ctime, sleep

def timefun(func):
    def wrappedfunc():
        print("%s called at %s"%(func.__name__, ctime()))
        func()
    return wrappedfunc

@timefun
def foo():
    print("I am foo")

foo()
sleep(2)
foo()
# 被装饰的函数有参数


from time import ctime, sleep

def timefun(func):
    def wrappedfunc(a, b):
        print("%s called at %s"%(func.__name__, ctime()))
        print(a, b)
        func(a, b)
    return wrappedfunc

@timefun
def foo(a, b):
    print(a+b)

foo(3,5)
sleep(2)
foo(2,4)
# 被装饰的函数有不定长参数


from time import ctime, sleep

def timefun(func):
    def wrappedfunc(*args, **kwargs):
        print("%s called at %s"%(func.__name__, ctime()))
        func(*args, **kwargs)
    return wrappedfunc

@timefun
def foo(a, b, c):
    print(a+b+c)

foo(3,5,7)
sleep(2)
foo(2,4,9)
# 被装饰的函数有返回值


from time import ctime, sleep

def timefun(func):
    def wrappedfunc():
        print("%s called at %s"%(func.__name__, ctime()))
        func()
    return wrappedfunc

@timefun
def foo():
    print("I am foo")

@timefun
def getInfo():
    return '----hahah---'

foo()
sleep(2)
foo()


print(getInfo())


######
# 执行结果:
foo called at Fri Nov  4 21:55:35 2016
I am foo
foo called at Fri Nov  4 21:55:37 2016
I am foo
getInfo called at Fri Nov  4 21:55:37 2016
None

# 如果修改装饰器为return func(),则运行结果:
foo called at Fri Nov  4 21:55:57 2016
I am foo
foo called at Fri Nov  4 21:55:59 2016
I am foo
getInfo called at Fri Nov  4 21:55:59 2016
----hahah---

# 总结:
    一般情况下为了让装饰器更通用,可以有return

# 装饰器带参数

from time import ctime, sleep

def timefun_arg(pre="hello"):
    def timefun(func):
        def wrappedfunc():
            print("%s called at %s %s"%(func.__name__, ctime(), pre))
            return func()
        return wrappedfunc
    return timefun


# @timefun_arg("itcast") 相当于如下步骤:
# 1.先执行 timefun_arg("itcast"),结果是 return 了 timefun 函数
# 2.@timefun
# 3.使用 @timefun 对 foo 进行装饰
# 以上3步,等同于执行了 timefun_arg("itcast")(foo)()
@timefun_arg("itcast")
def foo():
    print("I am foo")

@timefun_arg("python")
def too():
    print("I am too")

foo()
sleep(2)
foo()

too()
sleep(2)
too()
  • 实际开发示例
from functools import wraps


def admin_required(f):
    @wraps(f)
    def function(*args, **kwargs):
        # your code
        return f(*args, **kwargs)
    return function

@admin_required
def edit(id):
    pass


# 使用装饰器时,由于函数名和函数的doc发生了改变(被装饰后的函数其实已经是另外一个函数了),对测试结果有一些影响
# 所以,Python的functools包中提供了一个叫wraps的装饰器来消除这样的副作用
  • 类装饰器
    装饰器函数其实是这样一个接口约束,它必须接受一个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()
        
# 类装饰器语法,相当于执行了 test = Test(test)
# = 右边,是将 test 函数当做参数创建了一个 Test 类的对象
# = 左边,是将这个新创建的对象赋值给 test
@Test
def test():
    print("----test---")
    
# 此时 test 引用的是一个 Test 对象
# 所以调用 test(),实际调用的是该对象的 __call__ 方法  
test()
# 运行结果如下:

---初始化---
func name is test

---装饰器中的功能---
----test---
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容