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.