Python进阶——高阶函数、嵌套函数、闭包

第一部分 函数对象

  • 函数是Python中的第一类对象
    可以把函数赋值给变量
    对该变量进行调用,可实现原函数的功能
def square(x):
    return x**2


print(type(square))      # square 是function类的一个实例

pow_2 = square          # 可以理解成给这个函数起了个别名pow_2

print(pow_2(5))
print(square(5))
<class 'function'>
25
25
  • 可以将函数作为参数进行传递

第二部分 高阶函数

  • 满足下述条件之一的函数称之为高阶函数
    (1)接收函数作为参数
    (2)或者返回一个函数
def square(x):
    return x**2


def pow_2(fun):    # pow_2就是高阶函数,两个条件都满足
    return fun


f = pow_2(square)
print(f(8))
print(f == square)
64
True

第三部分 嵌套函数

  • 在函数内部定义一个函数
def outer():
    print("outer is running")
    
    def inner():
        print("inner is running")
        
    inner()


outer()
outer is running
inner is running

第四部分 闭包

4.1 闭包的定义

def outer():
    x = 1
    z = 10
    
    def inner():
        y = x+100
        return y, z
        
    return inner


f = outer()                # 实际上f包含了inner函数本身+outer函数的环境
print(f)

print(f.__closure__)         # __closure__属性中包含了来自外部函数的信息
for i in f.__closure__:
    print(i.cell_contents)

res = f()
print(res)
<function outer.<locals>.inner at 0x000001BE11B1D730>
(<cell at 0x000001BE0FDE06D8: int object at 0x00007FF910D59340>, <cell at 0x000001BE0FDE0A98: int object at 0x00007FF910D59460>)
1
10
(101, 10)
  1. 延伸了作用域的函数
  2. 如果一个函数定义在另一个函数的作用域内,并且引用了外层函数的变量,则该函数称为闭包
  3. 闭包是由函数及其相关的引用环境组合而成的实体(即:闭包=函数+引用环境)

4.2 nonlocal——声明范围

  • 一旦在内层函数重新定义了相同名字的变量,则变量成为局部变量
def outer():
    x = 1
    
    def inner():
        x = x+100
        return x
        
    return inner


f = outer()             
f()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-87-d2da1048af8b> in <module>
     10 
     11 f = outer()
---> 12 f()

<ipython-input-87-d2da1048af8b> in inner()
      3 
      4     def inner():
----> 5         x = x+100
      6         return x
      7 

UnboundLocalError: local variable 'x' referenced before assignment
  • 用nonlocal x 这个语句声明 x 引用的范围(跳过本层的引用),也就在后面执行 x = x+100 这一语句时,第二个 x 不再引用第一个 x,跳过了本层的引用,引用了上一层的 x = 200,再把这个 x 赋给本层定义的 x
def outer():
    x = 1
    
    def inner():
        nonlocal x
        x = x+100
        return x  
    return inner


f = outer()             
print(f())
101
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值