• python 中的闭包


    闭包这节课的第三个重点,我想再来介绍一下闭包(closure)。闭包其实和刚刚讲的嵌套函数类似,不同的是,
    
    
    这里外部函数返回的是一个函数,而不是一个具体的值。
    
    
    返回的函数通常赋于一个变量,这个变量可以在后面被继续执行调用。
    
    
    # -*- coding:utf-8 -*-
    # !/usr/bin/python
    def nth_power(exponent):
        def exponent_of(base):
            print base
            return base ** exponent
        return exponent_of  # 返回值是exponent_of函数
    
    x=nth_power(2)
    print x
    print type(x)
    
    C:Python27python.exe "C:/Users/TLCB/PycharmProjects/untitled2/python study/t7.py"
    <function exponent_of at 0x02092570>
    <type 'function'>
    
    返回的是一个函数
    
    # -*- coding:utf-8 -*-
    # !/usr/bin/python
    def nth_power(exponent):
        def exponent_of(base):
            print '------------------'
            print base
            print '------------------'
            return base ** exponent
        return exponent_of  # 返回值是exponent_of函数
    
    x=nth_power(2)
    print x
    print type(x)
    print dir(x)
    print x(3)
    
    
    C:Python27python.exe "C:/Users/TLCB/PycharmProjects/untitled2/python study/t7.py"
    <function exponent_of at 0x01DB2570>
    <type 'function'>
    ['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
    ------------------
    3
    ------------------
    9
    
  • 相关阅读:
    1059. C语言竞赛(20)
    1057. 数零壹(20)
    1056. 组合数的和(15)
    1054. 求平均值 (20)
    1052. 卖个萌 (20)
    1053. 住房空置率 (20)
    第五周课后作业02(动手动脑)
    课堂动手动脑
    课后作业
    课堂测试动手动脑
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13348383.html
Copyright © 2020-2023  润新知