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
    
  • 相关阅读:
    java 备忘
    C++ 命名规范 (转)
    代码格式规范
    using namespace 由来
    结构体数组 初始化(转)
    Java Servlet系列之Servlet生命周期
    进程,内存,管理 ps,pstree,top,free,vmstat,iftop,lsof,查看网速
    网络基础知识-
    进程作业管理2-kill,前后台作业,并行执行
    计划任务cron,date,时间同步ntp,chrony
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13348383.html
Copyright © 2011-2022 走看看