It’s possible to create classes that are similar to existing classes, but add or change some methods.
In this example, we create a Cat class with a speak method. We then create a Tiger class that’s a subclass of Cat. We add a roar method to Tiger.
Tiger objects can then do everything that Cat objects can do, but they also have a roar method. Tiger inherits the speak method from Cat.
class Cat:
def __init__(self, name):
self._name = name
def speak(self):
print(f"My name is {self._name}")
class Tiger(Cat):
def roar(self):
print(f"I AM {self._name}")
c1 = Cat("Tom")
c2 = Cat("Bob")
t1 = Tiger("Tiddles")
c1.speak()
c2.speak()
t1.speak()
t1.roar()
My name is Tom
My name is Bob
My name is Tiddles
I AM Tiddles
Overriding Methods
In Python, every method name in a class must be unique. You can’t have two methods with the same name in the same class, even if they have different parameters.
However, if we define a method in a subclass (derived class) that has the same name as a method in the superclass (parent class), it effectively replaces that method for objects of the subclass type.
This is called method overriding.
In this example, instead of adding a new roar method to tiger, we just override the speak method from Cat.
class Cat:
def __init__(self, name):
self._name = name
def speak(self):
print(f"My name is {self._name}")
class Tiger(Cat):
def speak(self):
print(f"I AM {self._name}")
c1 = Cat("Tom")
c2 = Cat("Bob")
t1 = Tiger("Tiddles")
c1.speak()
c2.speak()
t1.speak()
My name is Tom
My name is Bob
I AM Tiddles
Leave a Reply