美文网首页
闭包、装饰器

闭包、装饰器

作者: 奥特曼255 | 来源:发表于2018-05-27 22:32 被阅读0次

闭包

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

  • 优缺点
    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---

相关文章

  • python 高级 13闭包 装饰器

    闭包和装饰器 1.8 闭包和装饰器 学习目标 1. 能够说出闭包的定义形式 2. 能够说出装饰器的实现形式 ...

  • Python的自定义超时机制——装饰器的妙用

    装饰器 关于装饰器的入门,可以参考这篇文章:12步轻松搞定python装饰器简单来说,装饰器其实就是一个闭包(闭包...

  • Python装饰器-专题笔记

    学会装饰器,Python更进阶 函数作用域到闭包到装饰器讲解,及闭包和装饰器的运用。 [√] 慕课网Meshare...

  • Python-闭包和修饰器

    作用域 闭包 code: 装饰器 code: 装饰器案例 code:

  • Python 2 - 高级用法 - 装饰器

    Python 2 - 高级用法 - 装饰器 一谈到 装饰器,就离不开闭包 闭包 闭包就是能够读取其他函数内部变量的...

  • 装饰器

    1.装饰器的概念 装饰器是一个闭包:内层函数引用外层函数的变量(参数也算变量),然后返回内层函数,就是闭包。装饰器...

  • Python装饰器——初识

    上次讲了Python的闭包,今天来讲一下闭包的应用——装饰器 1. 装饰器是什么 什么叫装饰器?顾名思义,它是一个...

  • chapter7 函数式编程

    闭包 匿名函数 装饰器 偏函数

  • python装饰器

    学习了闭包的概念之后,再来学习装饰器就简单很多。装饰器就是闭包的一个应用 代码举例 但是装饰器在使用时分加载态和调...

  • [python] 装饰器学习

    很多python的代码都带有装饰器=。=现在不学以后也要学学一下装饰器 闭包 在学装饰器之前先看看python的闭...

网友评论

      本文标题:闭包、装饰器

      本文链接:https://www.haomeiwen.com/subject/dfhelftx.html