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

如何修复Pylint"错误的悬挂缩进"和PEP8 E121?

我试图正确缩进下面的代码:

RULES_LIST = [
    ('Name1', 1, 'Long string upto 40 chars'),
    ('Name2', 2, 'Long string upto 40 chars'),
    ('Name3', 3, 'Long string upto 40 chars'),
    ('Name4', 4, 'Long string upto 40 chars'),
    ('Name5', 5, 'Long string upto 40 chars'),
    ('Name6', 6, 'Long string upto 40 chars'),
    ('Name7', 7, 'Long string upto 40 chars'),
    ('Name8', 8, 'Long string upto 40 chars')
]
Run Code Online (Sandbox Code Playgroud)

pylint的抱怨Wrong hanging indentation.对于上面的代码,并PEP8抱怨E121: under-indented for hanging indent.

针对pylint的可能修复方法是将其更改为:

RULES_LIST = [\
    ('Name1', 1, 'Long string …
Run Code Online (Sandbox Code Playgroud)

python pep8 pylint indentation

27
推荐指数
3
解决办法
2万
查看次数

标签 统计

python ×2

closures ×1

indentation ×1

nested-function ×1

pep8 ×1

pylint ×1

scope ×1