Learn Python
>>> oop_fundamentals.inheritance

Inheritance in Python

#concept

Inheritance lets a new class (the subclass, or child) reuse the attributes and methods of an existing class (the superclass, or parent), while adding or overriding whatever makes it different. It's how Python models "this is a specific kind of that" relationships, like a Dog being a specific kind of Animal.

#how it works
1

class Child(Parent):

Defines a subclass that inherits everything the Parent class defines.

2

Inherited members work automatically

Every method and attribute from the parent is available, without rewriting any of it.

3

A subclass can add its own

New methods and attributes on top of what it inherited.

4

A subclass can override an inherited method

Defining a method with the same name makes its own version take priority.

5

super() reaches the parent’s version

Useful when overriding a method but still wanting the original behavior too.

#example
class Animal:
def __init__(self, name):
self.name = name
 
def speak(self):
print(f"{self.name} makes a sound")
 
class Dog(Animal):
def speak(self):
print(f"{self.name} barks")
 
generic = Animal("Generic Animal")
rex = Dog("Rex")
 
generic.speak()
rex.speak()
Output
Generic Animal makes a sound
Rex barks
1class Dog(Animal): makes Dog a subclass of Animal, inheriting __init__() automatically without redefining it.
2Dog overrides speak() with its own version — when called on a Dog instance, this version runs instead of Animal’s.
3generic.speak() calls Animal’s own speak(), since generic is a plain Animal, not a Dog.
4rex.speak() calls Dog’s overridden version, even though __init__() itself was inherited unchanged from Animal.
#use cases
Modeling an "is-a" relationship, like a Car and a Truck both being kinds of Vehicle
Reusing common setup and behavior across several related classes without duplicating code
Customizing specific behavior in a subclass while keeping everything else from the parent unchanged
Building on top of classes from a library or framework, extending their behavior instead of rewriting it

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.