函数调用返回结果连续次数

问题描述 投票:-1回答:1
def foo(bar):
    def looger():
        print 'hello from first satatement'
        parent()
        print 'hello from second satatement'
    return looger
def parent():
   print 'printing from parent function'
parent = foo('hi')
parent()

我遇到了问题。上面的代码从第一个语句连续时间返回结果hello,然后显示错误。我知道父函数没有被正确调用的错误,但我不明白为什么这给了我连续的结果。

python python-2.7
1个回答
2
投票

通过使用返回的记录器函数覆盖全局函数parent,您无意中创建了无限递归:

def foo(bar):
    def looger():
        print('hello from first satatement')
        parent() # This calls ....
        print('hello from second satatement')
    return looger
def parent():
   print('printing from parent function')
parent = foo('hi') # this function, what is not what you want
parent()

您可以通过重命名返回的函数来解决此问题:

def foo(bar):
    def looger():
        print('hello from first satatement')
        parent()
        print('hello from second satatement')
    return looger
def parent():
   print('printing from parent function')
p = foo('hi')
p()

打印:

hello from first satatement
printing from parent function
hello from second satatement
© www.soinside.com 2019 - 2024. All rights reserved.