Python Inheritance: Parent and Child Classes
What Is Inheritance in Python?
Inheritance lets you build a new class from a class that already exists. The new class, the child, gets every method of the old class, the parent, for free. Then you add only what's new.
Think of it like a family recipe. Grandma's cake recipe is the parent. Your chocolate cake starts from her recipe and adds cocoa. You don't copy out the whole recipe again; you write "Grandma's cake, plus cocoa".
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(self.name, "is eating")
class Dog(Animal):
def fetch(self):
print(self.name, "fetches the ball")
rocky = Dog("Rocky")
rocky.eat()
rocky.fetch()Rocky is eating Rocky fetches the ball
Dog has no __init__ and no eat() of its own, yet Dog("Rocky") and rocky.eat() work. They come from Animal.
The rules
- Write the parent's name in brackets:
class Dog(Animal):. - The child gets all the parent's methods, including
__init__and__str__. - The child can add new methods, like
fetch(). - The parent doesn't get the child's methods. An
Animalcan't fetch. - Define the parent first, then the child. Python reads from top to bottom.
Avoid: calling a child's method on a parent object
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def fetch(self):
print(self.name, "fetches the ball")
lucky = Animal("Lucky")
lucky.fetch()AttributeError: 'Animal' object has no attribute 'fetch'
Inheritance only flows down, from parent to child. lucky is a plain Animal, and fetch() lives in Dog.
Common beginner doubt: "How do I know when to use inheritance?" Use the "is a" test: a dog is an animal, a savings account is a bank account. If the sentence sounds right, inheritance fits.
A child class, like
class Dog(Animal):, gets all of the parent's methods and adds its own.