Home > Software engineering >  can i know the reason why my inheritance of python is not working?
can i know the reason why my inheritance of python is not working?

Time:08-22

For managing variables by class, I tried writing python code that using inheritance. However, my pool code is not working.

Practice.py

class Parents_A:
    def __init__(self, *args):
        self.A_a = 0
        self.A_b = np.array([])

    if args:
        self.set(*args)

@property
def As(self):
    return self.A_a

@property
def bs0(self) -> float:
    return self.A_b[0]

@property
def bs1(self) -> float:
    return self.A_b[1]

def set(self, A_a : float, A_b : np.ndarray):

    self.A_a = A_a 
    self.A_b = A_b 

    print('Setted!')


class Parents_B:
    def __init__(self, B_a, B_b):
        self.B_a = B_a
        self.B_b = B_b

class Child(Parents_B, Parents_A):
    def __init__(self, B_a, B_b, Parents_A):
        super().__init__(B_a, B_b, Parents_A)
        self.Iwant = Parents_A.As

main.py

if __name__ == '__main__':
    Data = Practice.Parents_A(1, ([0.9, 1.1]))
    calculator = Practice.Child(2, 3, Data)

Result is here:

TypeError: __init__() takes 3 positional arguments but 4 were given

Why this code is not working?

CodePudding user response:

Multiple inheritance is a risky thing.

class Child(Parents_B, Parents_A):
    def __init__(self, B_a, B_b, Parents_A):
        super().__init__(B_a, B_b, Parents_A)
        self.Iwant = Parents_A.As

super() over here will take the Parents_B init method which has two (Three including self).

Since you are passing Parents_A as a parameter, why inherit from Parents_A then? You can use the methods from Parents_A.

What is you purpose here for multiple inheritance??

CodePudding user response:

You inherit Child class from Parents_B and Parents_A but order matters. It means Child class take init method from the first class (Parents_B). Parents_B init method takes 2 arguments(B_a, B_b) but inside your Child class super method you provided 3 arguments (B_a, B_b, Parents_A).

  • Related