python高级之闭包

Image

python高级之闭包

什么是闭包?

闭包(closure)是函数式编程的重要的语法结构。闭包也是一种组织代码的结构,它同样提高了代码的可重复使用性。

当一个内嵌函数引用其外部作作用域的变量,我们就会得到一个闭包. 总结一下,创建一个闭包必须满足以下几点:

  • 必须有一个内嵌函数
  • 内嵌函数必须引用外部函数中的变量
  • 外部函数的返回值必须是内嵌函数

代码示例:

# 定义一个函数
def test(number):

    # 在函数内部再定义一个函数,并且这个函数用到了外边函数的变量,那么将这个函数以及用到的一些变量称之为闭包
    def test_in(number_in):
        print("in test_in 函数, number_in is %d" % number_in)
        return number+number_in
    # 其实这里返回的就是闭包的结果
    return test_in


# 给test函数赋值,这个20就是给参数number
ret = test(20)

# 注意这里的100其实给参数number_in
print(ret(100))

#注 意这里的200其实给参数number_in
print(ret(200))

运行结果:

in test_in 函数, number_in is 100
120

in test_in 函数, number_in is 200
220

闭包如何修改外部函数中的变量

python3的方法,通过nonlocal关键字

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/4/20 14:12
# @Author  : 一叶知秋
# @File    : 11.py
# @Software: PyCharm
def counter(start=0):
    def incr():
        nonlocal start
        start += 1
        return start

    return incr


def main():
    c1 = counter(5)
    print(c1())
    print(c1())

    c2 = counter(50)
    print(c2())
    print(c2())

    print(c1())
    print(c1())

    print(c2())
    print(c2())


if __name__ == '__main__':
    main()

结果:

6
7
51
52
8
9
53
54

闭包的高级应用之装饰器

装饰器(decorator)功能

  • 引入日志
  • 函数执行时间统计
  • 执行函数前预备处理
  • 执行函数后清理功能
  • 权限校验等场景
  • 缓存

装饰器示例

例1:无参数的函数

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/4/20 14:12
# @Author  : 一叶知秋
# @File    : 11.py
# @Software: PyCharm
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")


def main():
    foo()
    sleep(2)
    foo()


if __name__ == '__main__':
    main()

运行结果:

foo called at Mon Apr 20 14:25:35 2020
I am foo
foo called at Mon Apr 20 14:25:37 2020
I am foo

上面代码理解装饰器执行行为可理解成

foo = timefun(foo)
# foo先作为参数赋值给func后,foo接收指向timefun返回的wrapped_func
foo()
# 调用foo(),即等价调用wrapped_func()
# 内部函数wrapped_func被引用,所以外部函数的func变量(自由变量)并没有释放
# func里保存的是原foo函数对象

例2:被装饰的函数有参数

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/4/20 14:12
# @Author  : 一叶知秋
# @File    : 11.py
# @Software: PyCharm
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)


def main():
    foo(3, 5)
    sleep(2)
    foo(2, 4)


if __name__ == '__main__':
    main()

运行结果:

foo called at Mon Apr 20 14:32:37 2020
3 5
8
foo called at Mon Apr 20 14:32:39 2020
2 4
6

例3:被装饰的函数有不定长参数


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/4/20 14:12
# @Author  : 一叶知秋
# @File    : 11.py
# @Software: PyCharm

from time import ctime, sleep


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

    return wrapped_func


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


def main():
    foo(3, 5, 7)
    sleep(2)
    foo(2, 4, 9)


if __name__ == '__main__':
    main()

运行结果:

foo called at Mon Apr 20 14:36:56 2020
15
foo called at Mon Apr 20 14:36:58 2020
15

例4:装饰器中的return

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/4/20 14:12
# @Author  : 一叶知秋
# @File    : 11.py
# @Software: PyCharm

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


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


def main():
    foo()
    sleep(2)
    foo()
    print(getInfo())


if __name__ == '__main__':
    main()

运行结果:

foo called at Mon Apr 20 14:39:51 2020
I am foo
foo called at Mon Apr 20 14:39:53 2020
I am foo
getInfo called at Mon Apr 20 14:39:53 2020
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

例5:装饰器带参数,在原有装饰器的基础上,设置外部变量

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/4/20 14:12
# @Author  : 一叶知秋
# @File    : 11.py
# @Software: PyCharm

from time import ctime, sleep

# 下面的装饰过程
# 1. 调用timefun_arg("itcast")
# 2. 将步骤1得到的返回值,即time_fun返回, 然后time_fun(foo)
# 3. 将time_fun(foo)的结果返回,即wrapped_func
# 4. 让foo = wrapped_fun,即foo现在指向wrapped_func

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

        return wrapped_func

    return time_fun


@timefun_arg("hello")
def foo():
    print("I am foo")


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


def main():
    foo()
    sleep(2)
    foo()

    too()
    sleep(2)
    too()


if __name__ == '__main__':
    main()


运行结果:

foo called at Mon Apr 20 14:46:53 2020 hello
I am foo
foo called at Mon Apr 20 14:46:55 2020 hello
I am foo
too called at Mon Apr 20 14:46:55 2020 python
I am too
too called at Mon Apr 20 14:46:57 2020 python
I am too

例6:类装饰器

装饰器函数其实是这样一个接口约束,它必须接受一个callable对象作为参数,然后返回一个callable对象。在Python中一般callable对象都是函数,但也有例外。只要某个对象重写了 call() 方法,那么这个对象就是callable的。


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/4/20 14:12
# @Author  : 一叶知秋
# @File    : 11.py
# @Software: PyCharm


class Test():
    def __call__(self):
        print('call me!')


def main():
    t = Test()
    t()  # call me


if __name__ == '__main__':
    main()

类装饰器demo

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/4/20 14:12
# @Author  : 一叶知秋
# @File    : 11.py
# @Software: PyCharm


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


def main():
    test()


if __name__ == '__main__':
    main()


运行结果:

---初始化---
func name is test
---装饰器中的功能---
----test---

最后希望能对大家有帮助!

你可能感兴趣的:(python高级之闭包)