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

一.  函数内嵌 闭包

  • 在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
原文地址:https://www.cnblogs.com/v394435982/p/5193202.html