I have a dictionary of classes:
classes = { 'cls1' : Class1, 'cls2' : Class2 }
Here Class1, Class2 are Python classes I've defined, and each of them have methods foo() and bar().
Lets say I have another class called OtherClass. I want to iterate the above dictionary, and dynamically add some methods to the OtherClass as follows:
for k,v in classes.items():
setattr(OtherClass, 'foo_' + k, lambda x: v().foo())
setattr(OtherClass, 'bar_' + k, lambda x: v().bar())
This adds the methods foo_cls1, bar_cls1, foo_cls2, and bar_cls2 to OtherClass as expected. But it looks like calls to foo_cls1 and bar_cls1 get dispatched to foo_cls2 and bar_cls2 respectively. That is, the method definitions added later "overwrite" the previously added ones (assuming dictionary iteration order is cls1 followed by cls2). To further elaborate the problem, if I do the following after the above loop:
other = OtherClass()
other.foo_cls2() # Calls Class2.foo() -- Correct
other.foo_cls1() # Also calls Class2.foo() -- Unexpected behavior
other.bar_cls2() # Calls Class2.bar() -- Correct
other.bar_cls1() # Also calls Class2.bar() -- Unexpected behavior
Any idea what's going on, and how to fix it?