2

I have two classes that I want to inherit class A and class B, each requiring different values as arguments. How can I do that?

class A:
def __init__(self, a1, a2):
    print('A.__init__')
    super(A, self).__init__()
    
    self.a1 = a1
    self.a2 = a2

class B:
    def __init__(self, b):
        print('B.__init__')
        super(B, self).__init__()
    
        self.b = b

class C(A, B):
    def __init__(self, a1, a2, b):
        print('C.__init__')
        # call A.__init__(a1, a2)
        # call B.__init__(b)
kostas19
  • 21
  • 2
  • and remove ` super(A, self).__init__()` from class A and `super(B, self).__init__()` from class B – sittsering Sep 06 '21 at 12:12
  • Oh no, this option gives the following error ``` TypeError: __init__() missing 1 required positional argument: 'b' ``` – kostas19 Sep 06 '21 at 12:13
  • You can also use A.__init__(self, a1, a2), you were missing that self reference – m.oulmakki Sep 06 '21 at 12:14
  • @sittsering The first suggestion won't actually work (``super`` doesn't know that the ``a1, a2`` belong to A). The second goes completely against the point of cooperative inheritance (*every* method along the chain must invoke ``super`` to be cooperative). – MisterMiyagi Sep 06 '21 at 12:15
  • @sittsering, I cannot change class A and class B – kostas19 Sep 06 '21 at 12:16
  • 1
    @kostas19 If the classes aren't designed for multiple inheritance and you cannot change them, then you simply can't reliably use them with multiple inheritance. Have you considered composition over inheritance? – MisterMiyagi Sep 06 '21 at 12:18
  • @m.oulmakki, A.__init__(self, a1, a2) also gives an error `TypeError: __init__() missing 1 required positional argument: 'b'` and asks to pass b to the constructor of class A – kostas19 Sep 06 '21 at 12:19
  • @kostas19 `B.__init__(self, b)` – sittsering Sep 06 '21 at 12:24
  • @MisterMiyagi, to be honest, I haven't been working with python very long and was hoping to be able to use these classes as parents – kostas19 Sep 06 '21 at 12:25
  • 1
    @m.oulmakki, yes, I can call the constructor of class B. But when i calling a constructor of class A in this way calls a constructor of class B, which is not the behavior I expect – kostas19 Sep 06 '21 at 12:30

0 Answers0