When attempting to dynamically add functions to an object, I'm observing a weird situation.
During the process, it seems to be working fine, as every function returns the expected value.
But when calling each one of these functions again at the end of the process, they all seem to "point" to the last one added to the object.
Here is my code:
class Object:
pass
obj = Object()
print('during initialization:')
for n in range(3):
funcName = f'func{n}'
setattr(obj, funcName, lambda : n)
print(f'- {funcName} returns {getattr(obj, funcName)()}')
print('after initialization:')
print(f'- func0 returns {obj.func0()}')
print(f'- func1 returns {obj.func1()}')
print(f'- func2 returns {obj.func2()}')
And here is its printout:
during initialization:
- func0 returns 0
- func1 returns 1
- func2 returns 2
after initialization:
- func0 returns 2
- func1 returns 2
- func2 returns 2
Can anyone please help explaining this?
I guess that several similar questions have already been asked here a bunch of times, but I'm not really sure how to search for them.