Very occasionally, 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. In some languages (Objective-C shines in this regard with categories), you can do this very naturally. In Python, most people probably resort to monkey patching to accomplish this.
This is Probably An Anti-Pattern
I want to preface this with an admission that I have no idea if this will generally work (please comment if you know of a reason why it won’t!), and that I suspect that this is a horrible idea. And yet, here we go:
import copy class Base(object): def __init__(self): self.base_init = True def foo(self): return 'base foo' def bar(self): return 'base bar' class Child(Base): def __new__(cls, other): if isinstance(other, Base): other = copy.copy(other) other.__class__ = Child return other return object.__new__(cls) def __init__(self, other): self.child_init = True def bar(self): return 'child bar' b = Base() assert b.base_init == True assert b.foo() == 'base foo' assert b.bar() == 'base bar' assert b.__class__ == Base c = Child(b) assert c.base_init == True assert c.child_init == True assert c.foo() == 'base foo' assert c.bar() == 'child bar' assert c.__class__ == Child assert b.__class__ == Base
Have I made some glaring mistake? Is there something obviously wrong with this, other than the abuse of the language inherent in trying to do such a thing?