在编写粗略的memoized函数时,我遇到了这个 gotcha ;下面的两个片段说明了这个问题:
__foo = {}
def foobar(val):
if not val in __foo:
__foo[val] =123
else:
print ('Found!')
__foofoo = None
def foofoo(val):
if not __foofoo:
__foofoo =123
else:
print ('Exists!')
>>> foobar('1')
>>> foobar('1')
Found!
>>> foofoo(123)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foofoo
UnboundLocalError: local variable '__foofoo' referenced before assignment
为什么范围规则似乎有所不同(找不到__foo
,但找不到__foofoo
),具体取决于变量类型?