Sharing base object with inheritance

Posted by max on Stack Overflow See other posts from Stack Overflow or by max
Published on 2012-12-10T10:52:57Z Indexed on 2012/12/10 11:05 UTC
Read the original article Hit count: 136

I have class Base. I'd like to extend its functionality in a class Derived. I was planning to write:

class Derived(Base):
  def __init__(self, base_arg1, base_arg2, derived_arg1, derived_arg2):
    super().__init__(base_arg1, base_arg2)
    # ...
  def derived_method1(self):
    # ...

Sometimes I already have a Base instance, and I want to create a Derived instance based on it, i.e., a Derived instance that shares the Base object (doesn't re-create it from scratch). I thought I could write a static method to do that:

b = Base(arg1, arg2) # very large object, expensive to create or copy
d = Derived.from_base(b, derived_arg1, derived_arg2) # reuses existing b object

but it seems impossible. Either I'm missing a way to make this work, or (more likely) I'm missing a very big reason why it can't be allowed to work. Can someone explain which one it is?

[Of course, if I used composition rather than inheritance, this would all be easy to do. But I was hoping to avoid the delegation of all the Base methods to Derived through __getattr__.]

© Stack Overflow or respective owner

Related posts about python

Related posts about inheritance