好的,請耐心等待,我知道它會看起來非常複雜,但請幫我理解發生了什麼。Python嵌套函數中的局部變量
from functools import partial
class Cage(object):
def __init__(self, animal):
self.animal = animal
def gotimes(do_the_petting):
do_the_petting()
def get_petters():
for animal in ['cow', 'dog', 'cat']:
cage = Cage(animal)
def pet_function():
print "Mary pets the " + cage.animal + "."
yield (animal, partial(gotimes, pet_function))
funs = list(get_petters())
for name, f in funs:
print name + ":",
f()
給出:
cow: Mary pets the cat.
dog: Mary pets the cat.
cat: Mary pets the cat.
所以基本上,爲什麼我沒有得到三種不同的動物嗎?是不是將cage
'打包'到嵌套函數的本地範圍中?如果不是,調用嵌套函數如何查找局部變量?
我知道遇到這種問題通常意味着一個人「做錯了」,但我想知道發生了什麼。
嘗試'爲[ '貓', '狗', '牛']'動物。 ..我敢肯定有人會一起來解釋這一點,但它是Python gotcha的其中一個:) –