Search⌘ K
AI Features

Subclasses

Explore the concept of subclasses in Python to understand inheritance, method overriding, and polymorphism. This lesson helps you see how subclasses extend parent classes, use default methods, and customize behavior, empowering you to write more reusable and organized code.

We'll cover the following...

The real power of classes becomes apparent when you get into subclasses. You may not have realized it, but we’ve already created a subclass when we created a class based on object. In other words, we subclassed object. Now because object isn’t very interesting, the previous examples don’t really demonstrate the power of subclassing. So let’s subclass our Vehicle class and find out how all this works.

Python 3.5
class Car(Vehicle):
"""
The Car class
"""
#----------------------------------------------------------------------
def brake(self):
"""
Override brake method
"""
return "The car class is breaking slowly!"
if __name__ == "__main__":
car = Car("yellow", 2, 4, "car")
print(car.brake())
# 'The car class is breaking slowly!'
print(car.drive())
# "I'm driving a yellow car!"

For this example, we subclassed our Vehicle class. You ...