I write code where I’m given an object of some class (usually from a library call), but I wish to use additional methods on that class as though they had been defined there.
He’s a little light on the details of what he’s trying to accomplish exactly — the solution he provides ends up leaving the original instance untouched. If it’s ok to modify the original instance (or its class), then a more elegant solution might be:
class Base(object): def __init__(self): self.base_init = True def foo(self): return 'base foo' def bar(self): return 'base bar' def child_bar(self): return 'child bar' b = Base() # this overwrites all instances of from this point on. Base.bar = child_bar print b.bar() # prints 'child bar' # this overwrites the foo function of just an instance of Base import types def child_foo(self): return 'child foo' b.foo = types.MethodType(child_foo, b, b.__class__) print b.foo() # prints 'child foo' b_orig = Base() print b_orig.foo() # prints 'base foo'
In the first example, I’ve overwritten the bar method for all instances of class Base. In the second example, I’ve overwritten the foo method for just a single instance of Base. Admittedly, the types.MethodType call is a bit clunky (and I’ve never been able to commit it to memory, thank goodness for Google), but you could easily throw that into a handy function or decorator.