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

时间:2018-04-28 07:25:26

标签: python python-2.7

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,然后显示错误。我知道父函数没有被正确调用的错误,但我不明白为什么这会给我连续的结果。

1 个答案:

答案 0 :(得分: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