2

I'm hoping to inherit from two different classes that have different inputs into their __init__ methods. How do I properly inherit from them both?

Below is a simple example of what I'm trying to accomplish:

class a:
    def __init__(self):
        print("Hello")


class b(a):
    def __init__(self):
        super().__init__()
        print("World")


class c:
    def __init__(self, text):
        print(text)


class d(a, c):
    def __init__(self):
        super().__init__('Kronos')  # <-- This breaks (and understandably so)

While similar to many other questions of multiple inheritance (i.e. How does Python's super() work with multiple inheritance?), I'm looking for how to inherit from multiple classes with different inputs to their __init__.

Community
  • 1
  • 1
James Mertz
  • 8,459
  • 11
  • 60
  • 87
  • Possible duplicate of [How does Python's super() work with multiple inheritance?](http://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance) – Jared Mackey Oct 19 '15 at 22:03
  • consider adding an `*args, **kwargs` to your `__init__` methods – Chad S. Oct 19 '15 at 22:08

1 Answers1

4

I believe you can do it like below

class d(a,c):
   def__init__(self,text):
       a.__init__(self)
       c.__init__(self,text)
DreadfulWeather
  • 716
  • 3
  • 13
  • 1
    Ah, there we go. Yes that's what I'm looking for. For those interested, this not only executes the `print` statements, but if you were to have properties or methods they are properly inherited. – James Mertz Oct 19 '15 at 22:15
  • I would also reverse the a and c in execution. With the `super` method the `__mro__` order is left to right. Meaning that if I had a property defined in `a` and `c`, `a` would resolve the property first I believe. – James Mertz Oct 19 '15 at 22:16
  • 1
    This (unlike super) will not guarantee that each class in the inheritance tree is only initialized once. Look at the examples [here](https://rhettinger.wordpress.com/2011/05/26/super-considered-super/). Specifically the _Practical_Advice_, and either make them all have the same interface, or accept kwargs. – Chad S. Oct 19 '15 at 22:20
  • yes i think there is a better way with super but i dont remember why it is better and since i cant test it right now i edited to this one – DreadfulWeather Oct 19 '15 at 22:22
  • @ChadS. correct, but if you inherit in the reversed shown order, it should resolve similar to that of super. Execution time and memory management may take a hit. – James Mertz Oct 19 '15 at 22:22
  • 2
    @KronoS If you have classes A, B(A), C(B), D(A, C), your method will execute A's `__init__` twice. super() wont. – Chad S. Oct 19 '15 at 22:24
  • @ChadS. yes I agree. The accepted answer does not protect against roundtripping. – James Mertz Oct 19 '15 at 22:27