0

I have a class D, this class inherits the classes B and C, which both inherit A, but when I created an instance of class D this error occurred:

johni@johni-pc:~/Draft$ python3.4 main.py 
Traceback (most recent call last):
  File "main.py", line 35, in <module>
    d = D()
  File "main.py", line 31, in __init__
    super().__init__()
  File "main.py", line 19, in __init__
    super().__init__("pg")
TypeError: __init__() takes 1 positional argument but 2 were given

I don't understand this.

The classes B and C are initializing the parameter driver in class A. My file main.py:

class A:   
    def __init__(self, driver):
        self.driver = driver

    @property
    def driver(self):
        return self.__driver

    @driver.setter
    def driver(self, valor):
        self.__driver = valor

    def run_driver(self):
        print("I am executing with %s" % self.driver)

class B(A):

    def __init__(self):
        super().__init__("pg")


class C(A):

    def __init__(self):
        super().__init__("conn_pg")


class D(B, C):

    def __init__(self):
        super().__init__()


d = D()
print(d.run_driver())

Why did this error occur?

1 Answer 1

5

Note that super ensures that all superclass methods get called, according to the MRO (method resolution order - see e.g. How does Python's super() work with multiple inheritance?). D inherits from both B and C, so the following happens:

  • D() calls D.__init__
  • D.__init__ calls B.__init__
  • B.__init__ calls C.__init__ - here is the problem!
  • C.__init__ calls A.__init__ - we never get here

It is not clear why D inherits from both - you can't have two drivers, surely? If you do need to handle this, note that all __init__ methods should be written to take the same parameters, e.g. add:

def __init__(self, *args):
               # ^ ^ ^ ^ this part

to B and C.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.