Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify/override inherited class function in python?

I have the exact function name say_hello in both parent and inherited class. I want to specify the parameter name in the Kitten class but allows for user to specify the parameter in Cat class.

Is there a way to avoid the needs to repeat the line return ('Hello '+name) in the say_hello function in Kitten class?

Currently:

class Cat:
    def __init__(self):
        pass

    def say_hello(name):
        return ('Hello '+name)

class Kitten(Cat):
    def __init__(self):
        super().__init__()

    def say_hello(name='Thomas'):
        return ('Hello '+name)

x = Cat
print (x.say_hello("Sally"))
y = Kitten
print (y.say_hello())

Ideally:

class Cat:
    def __init__(self):
        pass

    def say_hello(name):
        return ('Hello '+name)

class Kitten(Cat):
    def __init__(self):
        super().__init__()

    def say_hello():
        return super().say_hello(name='Thomas') # Something like this, so this portion of the code doesn't need to repeat completely
like image 813
KubiK888 Avatar asked Jan 25 '19 19:01

KubiK888


People also ask

How do you override an inherited class in Python?

In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.

Can you override functions in Python?

Method overriding in Python is when you have two methods with the same name that each perform different tasks. This is an important feature of inheritance in Python. In method overriding, the child class can change its functions that are defined by its ancestral classes.

How do you stop overriding in Python?

"prevent <b>myself</b> from accidentally overriding" That's an odd use case. A feature of OO design is tidy and crisp allocation of responsibility. It should be very, very clear what functions are sensible in a given class. If it isn't crystal clear, you have too many responsibilities built into a single class.


1 Answers

The say_hello method should include self as the first parameter so that it can use the super() function to access the parent's say_hello method. You should also instantiate a class by calling it with parentheses:

class Cat:
    def say_hello(self, name):
        return 'Hello ' + name

class Kitten(Cat):
    def say_hello(self, name='Thomas'):
        return super().say_hello(name)

x = Cat()
print(x.say_hello("Sally"))
y = Kitten()
print(y.say_hello())

This outputs:

Hello Sally
Hello Thomas
like image 151
blhsing Avatar answered Oct 07 '22 15:10

blhsing