If you don’t like the behavior of a method in a superclass, you can simply define a method with the same name in the subclass:
class Kitten(Animal):
def eat(self, food):
print(f"{self.name}: I don’t like {food} at all!")
micka = Kitten('Micka')
micka.eat('kibble')
Sometimes, we may want to use the original functionality but also add something extra. We can do this using the special function super(), which allows us to call methods from the parent class. For example:
class Kitten(Animal):
def eat(self, food):
print(f"({self.name} looks at the {food} with fascination for a moment.)")
super().eat(food)
micka = Kitten('Micka')
micka.zjedz('kibble')
Be careful to pass all required arguments to the method called via super() (except for self, which is added automatically). We can also use this to modify arguments before passing them to the parent method.
class Snake(Animal):
def __init__(self, name):
name = name.replace('s', 'sss')
name = name.replace('S', 'Sss')
super().__init__(name)
stano = Snake('Stanislav')
stano.eat('mouse')
From these examples, we can see that super() can be combined with special methods like __init__.
__init__ and info() methods. Then create an object of the Car class and print its properties using the info() method.