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
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.
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.
"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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With