相关疑难解决方法(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
查看次数

是否存在追加和插入的原因?

我肯定不是我想成为的Python大师,而且我主要是在业余时间学习/试验,很可能我会为有经验的用户提出一个微不足道的问题...但是,我真的很想要理解,这是一个帮助我很多的地方.

现在,在适当的前提下,Python文档说:

4.6.3.可变序列类型

s.append(x)将x附加到序列的末尾(与s [len(s):len(s)] = [x]相同)

[...]

s.insert(i,x)在i给出的索引处将x插入s(与s [i:i] = [x]相同)

此外:

5.1.更多关于列表

list.append(x)将项添加到列表的末尾.相当于[len(a):] = [x].

[...]

list.insert(i,x)在给定位置插入一个项目.第一个参数是要插入的元素的索引,因此a.insert(0,x)插入列表的前面,而a.insert(len(a),x)等同于a.append( x).

所以现在我想知道为什么有两种方法可以做,基本上,同样的事情呢?那岂不是成为可能(和更简单),以只有一个append/insert(x, i=len(this))地方的i将是一个可选的参数,当不存在,就意味着添加到列表的末尾?

python insert append

6
推荐指数
1
解决办法
583
查看次数

标签 统计

python ×2

append ×1

closures ×1

insert ×1

nested-function ×1

scope ×1