dyao
dyao

Reputation: 1011

Inheritance - Calling methods within methods

I know the super() function allows you to call a parent method from a child class. So in this example:

class Exam():
    def __init__(self, a):
        self.a = a
        
    def show(self):
        print("This is from parent method")


class Quiz(Exam):
    def __init__(self, b, a):
        super().__init__(a)
        self.b = b
        
    def show(self):
        print("This is from child method")
        super().show()

q = Quiz('b', 'a')
q.show()

>>> 'This is from child method'
>>> 'This is from parent method'
   

What if I added another method called get_score to both the parent and child class like here:

class Exam():
    def __init__(self, a):
        self.a = a
        
    def show(self):
        print("This is from parent method")
        print (self.get_score())
    
    def get_score(self):
        return self.a
    
    
class Quiz(Exam):
    def __init__(self, b, a):
        super().__init__(a)
        self.b = b
        
    def show(self):
        print("This is from child method")
        super().show()
        print (self.get_score())
    
    def get_score(self):
        return self.b

q = Quiz('b', 'a')
q.show()

>>> 'This is from child method'
>>> 'This is from parent method'
>>> 'b'
>>> 'b'

I can understand why calling super().show() in the child class would return 'b' since I am overwriting the get_score() method.

However, is there a way to maintain the integrity of the parent class so that when I do call super().show()

I get this instead?

>>> 'This is from child method'
>>> 'This is from parent method'
>>> 'a'
>>> 'b'

Sorry in advance if this is bad design. Let me know what other alternatives I can take, even if it means I should the name of the method to avoid this kind of collision.

Upvotes: 3

Views: 60

Answers (1)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95948

Use name-mangling, which will prevent the name-collisions in the subclass :

class Exam():
    def __init__(self, a):
        self.a = a

    def show(self):
        print("This is from parent method")
        print (self.__get_score())

    def __get_score(self):
        return self.a

    get_score = __get_score


class Quiz(Exam):
    def __init__(self, b, a):
        super().__init__(a)
        self.b = b

    def show(self):
        print("This is from child method")
        super().show()
        print (self.__get_score())

    def __get_score(self):
        return self.b

    get_score = __get_score


q = Quiz('b', 'a')
q.show()

Upvotes: 2

Related Questions