相关疑难解决方法(0)

嵌套函数中的局部变量

好吧,请耐心等待我,我知道这看起来会非常令人费解,但请帮助我了解发生了什么.

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()
Run Code Online (Sandbox Code Playgroud)

得到:

cow: Mary pets the cat.
dog: Mary pets the cat.
cat: Mary pets the cat.
Run Code Online (Sandbox Code Playgroud)

所以基本上,为什么我没有得到三种不同的动物?是不是cage'打包'进入嵌套函数的局部范围?如果没有,对嵌套函数的调用如何查找局部变量?

我知道遇到这些问题通常意味着一个人"做错了",但我想了解会发生什么.

python closures scope nested-function

102
推荐指数
3
解决办法
9449
查看次数

标签 统计

closures ×1

nested-function ×1

python ×1

scope ×1