Either with
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)
or, more reliably, with
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)
In your original example, all generated functions access the same external variable fn
, which changes each time the loop starts. In the corrected examples, this is prevented.
source share