Home >Backend Development >Python Tutorial >Detailed explanation of Python function nesting

Detailed explanation of Python function nesting

高洛峰
高洛峰Original
2016-10-19 11:51:161513browse

The Python language allows when defining a function, its function body contains the complete definition of another function. This is what we usually call nested definition.

Instance 1:

def OutFun():         #定义函数OutFun(),
    m=3               #定义变量m=3;
    def InFun():      #在OutFun内定义函数InFun()
        n=4           #定义局部变量n=4
        print m+n     #m相当于函数InFun()的全局变量
     InFun()          #OutFun()函数内调用函数InFun()

Instance 2:

def InFun(m):
    n=4
    print m+n
def OutFun()
     m=4
     InFun(m)

Instance 2 first defines the function InFun(), and then defines the OutFun() function again. At this time, InFun() and OutFun() are completely independent For the two functions, InFun() is called again within the OutFun() function; in fact, the nesting effect in instance 1 and instance 2 is the same, but in two different forms of expression.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Use of redis under pythonNext article:Use of redis under python