• python闭包以及装饰器


    通俗的定义:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure)。它只不过是个“内层”的函数,由一个名字(变量)来指代,而这个名字(变量)对于“外层”包含它的函数而言,是本地变量;

     1 #示例一:
     2 #!/usr/bin/python 
     3 #encoding=utf-8 
     4 
     5 def add_a(num1):
     6     print "num1:%d" % num1 
     7     def add_b(num2):
     8         print "num2: %d" % num2
     9         return num1 + num2 
    10     return add_b        #返回的是函数名
    11 
    12 v = add_a(100)
    13 
    14 print v 
    15 print v(20)
    16 #执行结果:
    17 root@u163:~/cp163/python# python bibao2.py 
    18 num1:100
    19 <function add_b at 0x7f67482a35f0>
    20 num2: 20
    21 120
    22 
    23 #示例二
    24 #!/usr/bin/python 
    25 #encoding=utf-8
    26 
    27 def  makecounter(name):
    28     count = [0] 
    29     def counter():
    30         count[0] += 1
    31         print "hello",name,':', str(count[0])+" access!"
    32     return  counter
    33 
    34 test = makecounter("world")
    35 print test   #<function counter at 0x7f9d2ece57d0>
    36 test()
    37 test()
    38 test()
    39 
    40 #执行结果:
    41 root@u163:~/cp/python# python close_pkg_demo.py
    42 <function counter at 0x7f102c9497d0>
    43 hello world : 1 access!
    44 hello world : 2 access!
    45 hello world : 3 access!

    装饰器:

    #!/usr/bin/python 
    #encoding=utf-8
    
    """
    def foo():
        print 'in foo()'
    
    # 定义一个计时器,传入一个,并返回另一个附加了计时功能的方法'
    def  timeit(func):
        # 定义一个内嵌的包装函数,给传入的函数加上计时功能的包装
        def  wrapper():
            start = time.clock()
            func()
            end = time.clock()
            print 'used: ', end -start
        #将包装后的函数返回
        return  wrapper
    
    #将源函数修饰之后返回
    foo = timeit(foo)
    foo()
    """
    
    #Python中内置的装饰器有三个: staticmethod、classmethod 和property
    #"""使用语法糖来精简代码
    import time 
    def timeit(func):
        def wrapper():
            start = time.clock()
            func()
            end = time.clock()
            print "used: ", end - start
        return wrapper
    
    @timeit
    def foo():
        print "in foo()"
    
    foo()   #相当于1、先修饰函数(foo = timeit(foo) ), 2、再执行修饰之后的函数 
    #"""
    #执行结果:
    root@u163:~/cp/python# python deco_demo.py 
    in foo()
    used:  7.4e-05
  • 相关阅读:
    ThinkPHP框架 做个简单表单 添加数据例子__ACTION__ __SELF__
    ThinkPHP框架 系统规定的方法查询数据库内容!!同时也支持原生的SQL语句!
    ThinkPHP框架 基础 链接数据库
    ThinkPHP框架 3.2.2 获取系统常量信息 连接数据库 命名空间的理解
    ThinkPHP框架 自定义 Empty 方法保护本地信息不被暴露!!!
    Smarty模板保留缓存
    this指向
    phpcms v9 的表单向导功能的使用方法 附多个案例
    phpcms标签整理_当前栏目调用
    转载]PhpCms V9调用指定栏目子栏目文章的两种方法
  • 原文地址:https://www.cnblogs.com/chris-cp/p/4755321.html
Copyright © 2020-2023  润新知