闭包、作用域、函数嵌套

 

 1、闭包的定义

闭包常与函数嵌套、变量作用域等联系在一起。非专业地来说,闭包的表现形式是:一个外部函数里嵌套了一个内部函数,在主函数中调用外部函数时,外部函数会返回内部函数并赋值于一个变量,该变量记录外部函数的属性值,并允许该变量访问。一些公共的、已知的初始化、变量可以放到外部函数作用域,这样能避免代码的重复。

一个闭包示例如下所示(python2,如无特殊说明,以下代码均为python2):

# 实现累积计数功能
# 为何 now 为常量时不行呢,如 now = 0
def outer_function():
    now = [0]
    def inner_count():
        now[0] = now[0] + 1
        print now[0]
    return inner_count

count = outer_function()
count()
count()
count()

2、函数内部修改全局变量的方法


MIX = 1
def f():
    MIX += 1 #会报错:UnboundLocalError: local variable 'MIX' referenced before assignment
f()

MIX = 1
def f():
    global MIX # 这会告诉编译器在该函数的使用的变量MIX已经在全局中声明了,使用那个全局变量就行
    MIX += 1
    print MIX # 打印2
f()

3、函数嵌套的作用

函数嵌套有两大作用

(1)减少代码冗余

# -*- coding:UTF-8 -*-


# 假设用递归实现累加运算,为了程序的鲁棒,在进行累加前需要检查输入是否正确

# 不使用函数嵌套,每一次递归都会重新判断一下异常
def accumulate(input):
    if not isinstance(input, int):
        raise Exception('Input must be integer')

    if input < 0:
        raise Exception('Input must be larger than zero')

    if input == 1:
        return 1

    return input + accumulate(input-1)




# 使用函数嵌套,只需判断一次异常
def accumulate_nest(input):
    if not isinstance(input, int):
        raise Exception('Input must be integer')

    if input < 0:
        raise Exception('Input must be larger than zero')

    def inner(input):
        if input == 1:
            return 1
        return input + inner(input-1)
    return inner(input)

print accumulate_nest(3)

(2)提高代码安全性

内部函数接口只会暴露给其嵌套的外部函数,其它地方是无法访问内部函数的,这样就可以在内部函数中处理一些私密的信息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值