• python 闭包 闭包与装饰器之间的关系


    一、一个闭包的实际应用例子

    1 def func(a, b):
    2     def inner(x):
    3         return a * x + b
    4     return inner
    5 
    6 inn = func(1, 1)
    7 print(inn(1))
    8 inn2 = func(-1, 1)
    9 print(inn2(1))

    二、闭包传递的参数为函数。

     1 def func(func_temp):
     2     def inner(x):
     3         func_temp(x)
     4     return inner
     5 
     6 
     7 def test(arg):
     8     print('test func. %s' % arg)
     9 
    10 
    11 inn = func(test)
    12 inn('xxx')

    三、闭包与修饰器的关系,以下2个例子是等效的。

     1 def check(func):
     2     def inner():
     3         print('def')
     4         func()
     5     return inner
     6 
     7 def foo():
     8     print('abc')
     9 
    10 foo = check(foo)    # 闭包
    11 foo()
     1 def check(func):
     2     def inner():
     3         print('def')
     4         func()
     5     return inner
     6 
     7 #foo = check(foo)
     8 @check              # 语法糖,装饰器
     9 def foo():
    10     print('abc')
    11 
    12 foo()
  • 相关阅读:
    进程同步&&进程互斥
    CHAP4 字符串和格式化输入输出
    记录学习到的内容
    数据链路层 差错控制
    二叉树的顺序存储
    Java复习笔记
    Stream流
    函数式接口
    网络编程
    接口,多态,抽象类总结
  • 原文地址:https://www.cnblogs.com/gundan/p/8149544.html
Copyright © 2020-2023  润新知