Home > Blockchain >  how do i call the parent method if i have a function with the same name in the current class (if pos
how do i call the parent method if i have a function with the same name in the current class (if pos

Time:09-27

I was reading on method overriding and in other languages, it seems that to be completely overridden, the method has to have the same signature (parameters, return type... etc)

so I was trying to check if that's how it worked with python and I tried the next code

class Person():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def print_name(self, last_name):
        print(self.name   " "   last_name)

class Superhero(Person):
    def __init__(self, name, age, power):
        super().__init__(name, age)
        self.power = power

    def print_name(self):
        print(self.name)


human = Person("Ron", 23)
super_human = Superhero("Superman", 30, "Flying")

human.print_name("Wesley")
super_human.print_name("Kent")

and I'm receiving an error on the super_human.print_name("Kent") part that it takes one argument but I'm passing two, I know the MRO exist in python where I look into (object > class > parent class), so I'm wondering if there's a way that I can call the print_name() function that exist in the parent class not the current one, since they take different parameters.

CodePudding user response:

If you're going to override a base class method, the arguments should always be a compatible with what you're overriding. Thats one of the basic guidelines that can be taken from the Liskov Substitution Principle

If you want the function to act differently than the super method if the argument wasn't supplied, then you could do something like this:

class Superhero(Person):
    def __init__(self, name, age, power):
        super().__init__(name, age)
        self.power = power

    def print_name(self, last_name=None):
        if last_name is None:
            print(self.name)
        else:
            super().print_name(last_name)

This keeps the contract defined by the super method, and now allows the Superhero class to handle the values differently. If you always want to throw away the last name, then just do:

class Superhero(Person):
    def __init__(self, name, age, power):
        super().__init__(name, age)
        self.power = power

    def print_name(self, last_name=None):
        print(self.name)
  • Related