zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    PAT L3-021 神坛
    2019.07.08【NOIP提高组】模拟 A 组 总结
    2019.07.06【NOIP提高组】模拟 A 组 总结
    2019.07.05【NOIP提高组】模拟 A 组 总结
    jzoj 1287. 躲雨
    jzoj 4614. 【NOIP2016模拟7.12】字符串
    jzoj 3317. 【BOI2013】管道
    2019.07.04【NOIP提高组】模拟 A 组
    jzoj 3316. 【BOI2013】非回文数字
    jzoj 4616. 【NOI2016模拟7.12】二进制的世界
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13348383.html
Copyright © 2011-2022 走看看