Reusing a class
Inheritance lets a new class start with everything another class has, and then add or change things.
Think of it like this: Cars, bikes and buses are all vehicles. They share things (wheels, a speed), but each has its own extras.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
def introduce(self):
print(f"I am {self.name} and I say {self.speak()}")
class Cat(Animal):
def speak(self):
return "Meow"
class Cow(Animal):
def speak(self):
return "Moo"
for pet in [Cat("Kitty"), Cow("Gauri")]:
pet.introduce()Output
I am Kitty and I say Meow I am Gauri and I say Moo
class Cat(Animal):means Cat inherits from Animal. Animal is the parent, Cat is the child.- Cat didn't write
__init__orintroduce– it got them from Animal. - Cat writes its own
speak. This is called overriding a method.
Adding to the parent's setup with super()
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class Manager(Employee):
def __init__(self, name, salary, team):
super().__init__(name, salary)
self.team = team
boss = Manager("Kabir", 90000, ["Asha", "Ravi"])
print(boss.name, "manages", len(boss.team), "people")Output
Kabir manages 2 people
super().__init__(...) runs the parent's setup first, then the child adds its own attribute.
Tip: Don't worry if classes feel strange at first. Write a few small ones – a
Pet, aPlayer, aProduct– and they'll start to click.