Python嵌套函数的使用方法

125 阅读1分钟

Python中的函数可以嵌套在其他函数中。

在一个函数内部定义的函数只在该函数内部可见。

这对于创建对一个函数有用,但在该函数之外没有用的实用程序很有用。

你可能会问:如果这个函数没有危害,我为什么要 "隐藏 "它?

其一,因为最好是隐藏对一个函数局部有用的功能,而在其他地方没有用。

另外,还因为我们可以利用闭包(后面会有更多介绍)。

这里有一个例子。

def talk(phrase):
    def say(word):
        print(word)

    words = phrase.split(' ')
    for word in words:
        say(word)

talk('I am going to buy the milk')

如果你想从内部函数中访问外部函数中定义的变量,你首先需要将其声明为nonlocal

def count():
    count = 0

    def increment():
        nonlocal count
        count = count + 1
        print(count)

    increment()

count()

这在闭包中尤其有用,我们后面会看到。