Home > Net >  Inheriting from multiple classes
Inheriting from multiple classes

Time:10-26

class One:
    def __init__(self):
        self.one = 1


class Two:
    def __init__(self):
        self.two = 2


class Three(One, Two):
    def __init__(self):
        self.three = 3
        super().__init__()


obj = Three()

print(obj.one)
print(obj.two)
print(obj.three)

i am currently self learning OOP, i am having a hard time understanding why the object was able to print the attribute from Class One but not also the one from Class Two despite me using the super function, the error raised is AttributeError: 'Three' object has no attribute 'two'. How do we inherit from multiple classes?

CodePudding user response:

super().__init__() in Three will only refer to the first class in Method Resolution Order. In order to call all the __init__, you'd need to do super() in all of them:

class One:
    def __init__(self):
        self.one = 1
        super().__init__()


class Two:
    def __init__(self):
        self.two = 2
        super().__init__()

Or, if you don't want to / can't modify parent class signatures, you refer to the classes directly instead of using super, so they will all be called regardless of MRO:

class Three(One, Two):
    def __init__(self):
        self.three = 3
        One.__init__()
        Two.__init__()

CodePudding user response:

class One:
    def __init__(self):
        self.one = 1
        super().__init__()
class Two:
    def __init__(self):
        self.two = 2
        super().__init__()
class Three(One,Two):
    def __init__(self):
        self.three = 3
        super().__init__()
    


obj = Three()

print(obj.one)
print(obj.two)
print(obj.three)

use super().__init__method in every class. if you dont want to use it. you can call init methods of class one and class two in init method of class three.

  • Related