I would like to add some methods to a class definition at runtime. However, when running the following code, I get some surprising (to me) results.
test.py
class klass(object):
pass
for i in [1,2]:
def f(self):
print(i)
setattr(klass, 'f' + str(i), f)
I get the following when testing on the command line:
>>> import test
>>> k = test.klass()
>>> k.f1()
2
>>> k.f2()
2
Why does k.f1() return 2 instead of 1? It seems rather counter intuitive to me.
notes
This test was done using python3.0 on a kubuntu machine.
It’s the usual problem of binding — you want early binding for the use of
iinside the function and Python is doing late binding for it. You can force the earlier binding this way:or by wrapping f into an outer function layer taking i as an argument: