首页 > 编程语言 > 详细

python 内嵌函数, 闭包, 函数装饰器

时间:2016-02-16 18:41:13      阅读:145      评论:0      收藏:0      [点我收藏+]

一.  函数内嵌 闭包

  • 在python中,函数可以作为返回值, 可以给变量赋值.
  • 在python中, 内置函数必须被显示的调用, 否则不会执行.
    #!/usr/bin/env python
    #-*- coding: utf-8 -*-
    
    def foo():
        m = 4
        def bar():
            n = 3
            d = m + n
            return d
        return bar
    
    test = foo()
    print test()
    
    #结果:
    7
    #!/usr/bin/env python
    #-*- coding: utf-8 -*-
    
    def foo():
        m = 4
        def bar():
            n = 3
            m = m + n
            return m
        return bar
    
    test = foo()
    print test()
    
    #结果
    UnboundLocalError: local variable m referenced before assignment
    
    在python2中 把m换成list就不会出现这样的错误,  在python3中,nonlocal 可以解决这个问题, 没搞清楚其中的原理

二、嵌套函数和它的变种(装饰器)


以下两端代码,作用是相同的,

def test(n):
    return n  

def test_pro(func):
    y = 100
    def warpper(x):
        return func(y) * x

    return warpper 

f = test_pro(test)
print f(4)

#结果
400

将上边代码改写:

def test_pro(func):
    y = 100
    def warpper(x):
        return func(y) * x

    return warpper

@test_pro
def test(n):
    return n

print test(4)

#结果
400

 

python 内嵌函数, 闭包, 函数装饰器

原文:http://www.cnblogs.com/v394435982/p/5193202.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!