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,然后显示错误。我知道父函数没有被正确调用的错误,但我不明白为什么这给了我连续的结果。
通过使用返回的记录器函数覆盖全局函数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