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

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

 

相关文章:

  • 2022-12-23
  • 2021-09-06
  • 2021-04-28
  • 2021-10-13
  • 2021-07-04
  • 2022-12-23
  • 2021-05-16
猜你喜欢
  • 2021-07-16
  • 2021-10-31
  • 2021-12-19
  • 2021-06-20
相关资源
相似解决方案