6

我对这种范围行为感到困惑:

class Bar:
    def __init__(self):
        for fn in ["open","openW","remove","mkdir","exists","isdir","listdir"]:
            print "register", fn
            def func_wrapper(filename):
                print "called func wrapper", fn, filename
            setattr(self, fn, func_wrapper)

bar = Bar()
bar.open("a")
bar.remove("b")
bar.listdir("c")

这给出了输出:

register open
register openW
register remove
register mkdir
register exists
register isdir
register listdir
called func wrapper listdir a
called func wrapper listdir b
called func wrapper listdir c

但我原以为func_wrapper这总是正确的功能。我知道的范围func_wrapper是整个函数,但我在每次循环迭代中重新定义它,最后一个实例被保存在属性中。我也尝试在func_wrapper = None下面添加,setattr但这没有帮助(我也会想知道......)。

我瞎了吗?我什至不知道如何解决/解决这个问题。

4

1 回答 1

6

要么与

class Bar:
    def __init__(self):
        for fn in ["open","openW","remove","mkdir","exists","isdir","listdir"]:
            print "register", fn
            def func_wrapper(filename, fn=fn):
                print "called func wrapper", fn, filename
            setattr(self, fn, func_wrapper)

或者,更稳健地,使用

def mkwrapper(fn):
    def func_wrapper(filename):
        print "called func wrapper", fn, filename
    func_wrapper.__name__ = fn
    return func_wrapper

class Bar:
    def __init__(self):
        for fn in ["open","openW","remove","mkdir","exists","isdir","listdir"]:
            print "register", fn
            func_wrapper = mkwrapper(fn)
            setattr(self, fn, func_wrapper)

在您的原始示例中,所有生成的函数都访问相同的外部变量fn,该变量在每次循环运行时都会发生变化。在更正的示例中,可以防止这种情况发生。

于 2012-06-22T22:33:22.007 回答