Dynamically Add Methods to Existing Python Classes

from blog damnever's blog, | ↗ original
Adding an instance attribute dynamically is as simple as: obj.a = 1 or setattr(obj, 'a', 1). So easy! However, when it comes to dynamically adding methods, the problem arises. Here, a method is dynamically added to an instance: >>> class A(object): ... pass ... >>> def hello(self): ... print "hello" ... >>> a = A() >>> a.hello = hello...