Home > OS >  how to inherit init() function and other methods in the grandchild.?
how to inherit init() function and other methods in the grandchild.?

Time:11-25


class Parent:
    def __init__(self,name,lastname):
        self.name = name
        self.lastname = lastname
    def getname(self):
        return "{} {}".format(self.name,self.lastname)
class Child1(Parent):
    def __init__(self,name,lastname,age):
        self.age = age
        super().__init__(name,lastname)
    def getnage(self):
        return [super().getname(),self.age]
class Child2(Parent):
    def __init__(self,name,lastname,s):
        self.s = s
        super().__init__(name,lastname)
    def getsname(self):
        return [super().getname(), self.s] 
class Grandchild(Child1,Child2):
    def __init__(self,name,lastname,age,s,address):
        self.address = address
        Child1.__init__(self,name,lastname,age)
        Child2.__init__(self,name.lastname,s)
    def info(self):
        return [super().getnage()[0],super().getnage()[1],super().getsname(),self.address]

In the Grandchild I try to inherit init function and others methods from the Child1 and Child2 classes, which having common parent class Parent.

CodePudding user response:

I had to clean up a couple of constructors and explicitly used the class name to init instead of super. This seems to give the output you are expecting:

    class Parent:
        def __init__(self, name, lastname):
            self.name = name
            self.lastname = lastname
    
        def getname(self):
            return "{} {}".format(self.name, self.lastname)
    
    
    class Child1(Parent):
        def __init__(self, name, lastname, age):
            Parent.__init__(self, name, lastname)
            self.age = age
    
        def getnage(self):
            return [self.getname(), self.age]
    
    
    class Child2(Parent):
        def __init__(self, name, lastname, s):
            self.s = s
            super().__init__(name, lastname)
    
        def getsname(self):
            return [self.getname(), self.s]
    
    
    class Grandchild(Child1, Child2):
        def __init__(self, name, lastname, age, s, address):
            self.address = address
            Child1.__init__(self, name, lastname, age)
            Child2.__init__(self, name, lastname, s)
    
        def info(self):
            return [self.getnage()[0], self.getnage()[1], self.getsname(), self.address]
    
    
    if __name__ == '__main__':
        test = Grandchild( 'lee', 'jones', 52, "huh?", "here" )
        print(test.info())

Outputs: ['lee jones', 52, ['lee jones', 'huh?'], 'here']

  • Related