Inheritance is an advanced Python concept that you probably won’t use when starting out. Most beginner programs work perfectly fine without it. However, as your projects grow, inheritance can make your code much cleaner by avoiding repetition.
Don’t worry if inheritance feels complex at first. Focus on understanding basic classes, and come back to inheritance when you find yourself writing similar classes with shared functionality.
Inheritance lets you create new classes based on existing ones. The new class (child) gets everything from the parent class, plus can add its own stuff.Think of it like this:
All dogs are animals (dogs inherit from animals)
Dogs have everything animals have, plus dog-specific things
# Parent class - general animalclass Animal: def __init__(self, name): self.name = name def eat(self): return f"{self.name} is eating" def sleep(self): return f"{self.name} is sleeping"# Child class - specific animalclass Dog(Animal): def bark(self): return f"{self.name} says woof!"# Create a dog - using positional argumentmy_dog = Dog("Buddy")# Or with named argumentmy_dog2 = Dog(name="Max")# Dog can do animal things (inherited)print(my_dog.eat()) # Buddy is eatingprint(my_dog.sleep()) # Buddy is sleeping# Dog can also do dog thingsprint(my_dog.bark()) # Buddy says woof!
class Animal: def __init__(self, name): self.name = name self.is_pet = Trueclass Dog(Animal): def __init__(self, name, breed): super().__init__(name) # Pass name to parent's __init__ self.breed = breed # Dog-specific attribute def describe(self): return f"{self.name} is a {self.breed}"# Create dogs with breeds - positional argumentsgolden = Dog("Buddy", "Golden Retriever")# Or with named arguments (clearer)poodle = Dog(name="Max", breed="Poodle")print(golden.describe()) # Buddy is a Golden Retrieverprint(golden.is_pet) # True (inherited from Animal)
super().__init__() calls the parent class’s __init__ method. This ensures the parent class sets up its attributes properly before the child class adds its own.