Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Two-Parent Inheritance in Python

If we do class inheritance, I’d say a reasonable assumption would be that this code would work:

 class AddsFunct:
    def __init__(self):
        self.greet1 = "hello"


class AddsFunct2:
    def __init__(self):
        self.greet2 = "world"


class FullName(AddsFunct, AddsFunct2):
    def __init__(self, name, surname):
        super(AddsFunct, self).__init__()
        super(AddsFunct2, self).__init__()
        self.name = name
        self.surname = surname

    def printer(self):
        print(self.greet1 + " " + self.name + " " + self.surname + " " + self.greet2)


fullname = FullName("John", "Doe")
fullname.printer()

The only way I could make this run is changing the super calls to:

class FullName(AddsFunct, AddsFunct2):
    def __init__(self, name, surname):
        super().__init__()
        super(AddsFunct, self).__init__()
        self.name = name
        self.surname = surname

How is this supposed to be done in a clean and simple way ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The class you pass to super will point to where in the MRO (Method Resolution Order) will start looking for the parent method. Instead, you can simply refer to classes directly.

class FullName(AddsFunct, AddsFunct2):
    def __init__(self, name, surname):
        AddsFunct.__init__(self)
        AddsFunct2.__init__(self)
        self.name = name
        self.surname = surname

The another option, which avoids the need to refer to the classes directly, but requires changing all the parent classes, is to make them call super by themselves:

class AddsFunct:
    def __init__(self):
        super().__init__()
        self.greet1 = "hello"


class AddsFunct2:
    def __init__(self):
        super().__init__()
        self.greet2 = "world"


class FullName(AddsFunct, AddsFunct2):
    def __init__(self, name, surname):
        super().__init__()
        self.name = name
        self.surname = surname

This will call all the supers in MRO, eventually ending up at objects class __init__.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading