Python内部函数不打印外部函数中初始化的值



在以下代码中,'消息'变量在P1中打印了正确的值,但在P2中不打印任何内容。我遵循了一个编写此代码的教程,看起来与他写的非常相似。我正在使用Python 3.6。有人可以解释为什么吗?

def outer_function(msg):
    message = msg 
    print(message) #P1
def inner_function():
    print(message) #P2
    return inner_function()

屏幕屏幕抓取教程中的确切代码

是 @see提到的...与表格凹痕相距,您的代码将导致堆栈溢出:

也许您的代码应该如下:

def outer_function(msg):
    message = msg
    print(message) #P1
    def inner_function():
        print(message) #P2
    return inner_function()
outer_function("hello")

除了不正确的凹痕(我认为是错字(,您的 inner_function递归地自称为永远,所以我希望这里有堆栈溢出。

通常闭合只是内在函数,即使外部函数脱离范围,也可以记住外部函数的变量。

所以我希望您的代码能适当地缩进了应该像应该的一样工作。

def outer_function(msg): 
      message = msg print(message) #P1 
      def inner_function():
            print(message) #P2 
      return inner_function()

在这里,即使outer_function脱离范围

,可变消息也会被内部函数记住

尝试以下:

class A:
    message = None
    def outer_function(self, msg):
        self.message = msg
        print(self.message) #P1
    def inner_function(self):
        print(self.message) #P2

然后在您的Python外壳中:

>>> a = A()
>>> a.inner_function()
None
>>> a.outer_function('Hello!')
Hello!
>>> a.inner_function()
Hello!

最新更新