0

I have a diamond structure of classes in Python and I need to inherit the variables of the three superclasses in the last one. This is an example of this problem :

class Base:
    def __init__(self, a, b):
        self.a = a
        self.b = b

class second(Base):
    def __init__(self, a, b, c):
        super().__init__(a, b)
        self.c = c

class second2(Base):
    def __init__(self, a, b, Q):
        super().__init__(a, b)
        self.Q = Q

class third(second, second2):
   def __init__(self, a, b, c, Q, d):
        super().__init__(a, b, c, Q)
        self.d = d

by compiling this example I don't obtain any errors, but if i try to create an istance of the third class like this :

a = 1
b = 2
c = 3
Q = 4
d = 5
t = third(a, b, c, Q, d)

I receive this error :

line 26, in <module>
    t = third(a, b, c, Q, d)
line 18, in __init__
    super().__init__(a, b, c, Q)
TypeError: second.__init__() takes 4 positional arguments but 5 were given

How can i make this code run correctly ? So how can I inherit from class "third" the variables of the classes Base, second and second2 and add one variables "d" ?

Simospa
  • 23
  • 4
  • 1
    Does this answer your question? [How does Python's super() work with multiple inheritance?](https://stackoverflow.com/questions/3277367/how-does-pythons-super-work-with-multiple-inheritance) – asongtoruin Jul 04 '22 at 11:29
  • no one of these examples solve this problem with the variables – Simospa Jul 04 '22 at 11:38

1 Answers1

0

I'd avoid using super() in this case, as your init() definitions don't even have the same number of args, this being a possible cause to your issue. However, you'll end up with your Base init being called twice, which is not something you'd generally want.

class Base:
    def __init__(self, a, b):
        self.a = a
        self.b = b

class second(Base):
    def __init__(self, a, b, c):
        Base.__init__(self, a, b)
        self.c = c

class second2(Base):
    def __init__(self, a, b, Q):
        Base.__init__(self, a, b)
        self.Q = Q

class third(second, second2):
   def __init__(self, a, b, c, Q, d):
        second.__init__(self, a, b, c)
        second2.__init__(self, a, b, Q)
        self.d = d


a = 1
b = 2
c = 3
Q = 4
d = 5
t = third(a, b, c, Q, d)
print(f"{t.a} {t.b} {t.c} {t.Q} {t.d}")

Hope that helps.

Deck451
  • 61
  • 5