【发布时间】:2015-03-23 14:56:39
【问题描述】:
foo 会在函数 def 中为 foo 知道 foo,这完全出乎意料(至少对我而言)。这到底是怎么回事?
>>> def foo(x):
... print "wow"
... print globals().get('foo', 'sorry')
... return foo
...
>>> f = foo(3)
wow
<function foo at 0x10135f8c0>
>>> f
<function foo at 0x10135f8c0>
这是python惰性求值的某种效果吗?它首先构建函数代码并将其放入globals,但实际上稍后在调用它时构建函数?哇……这是什么形式的蟒蛇魔法?
当然,这便于递归……这可能是语言中出现这种情况的原因……
>>> def bar(x):
... return bar(x)
...
>>> bar(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in bar
File "<stdin>", line 2, in bar
File "<stdin>", line 2, in bar
...snip...
File "<stdin>", line 2, in bar
File "<stdin>", line 2, in bar
RuntimeError: maximum recursion depth exceeded
【问题讨论】:
-
“但后来实际构建函数”是什么意思?该功能已经“构建”(定义)。我没有看到任何魔法。
-
你习惯什么语言?因为我没有看到任何魔法,递归也没有。你把这和什么比较?
-
我不明白你的问题。你会怎么做递归?为什么这使得无限递归比任何其他支持递归的语言更容易?
-
@IsmailBadawi:呃……?谁说过其他语言?
-
不,我在询问使名称引用在函数定义内部有效的过程......以便递归成为可能。正如我的问题所述,我意识到引擎盖下有字节码。
标签: python