I need to dynamically add a class method with a name determined at runtime, and also an internal state that is determined at runtime. Here is the simplest example I can cook up:
class foo(): pass def h(self): # h() is just a placeholder until we can do setattr() state = 'none' return state setattr(h,'state','something') setattr(foo,'bar',h) del(h) print(dir(foo)) # includes 'bar' print(dir(foo.bar)) # includes 'state' print(getattr(foo.bar,'state')) # 'something' f = foo() print(getattr(f.bar,'state')) # 'something' # all is well up to here, but now we go awry print(f.bar()) # 'none'
In the last line, the bar() return statement seems to be bound to the original definition in h() rather than its new context in foo. I have tried numerous things, and looked at introspection and other topics in stack overflow, but come up empty. How can I modify this code so that the last line yields 'something'?