CodeBlanks Logo Icon CodeBlanks

Inheritance basics

Learn inheritance with class Child(Parent).

Inheritance

Inheritance is when a class takes on the attributes and methods of another class. The child class writes the parent class name in parentheses.

Example: class Dog(Animal): pass. Here Dog is the child, Animal is the parent. Dog inherits all methods of Animal. The parent class must be defined first. Inheritance reduces code duplication.

Parent first

To inherit, the parent class must be defined before the child. Python reads top to bottom; writing an undefined name in parentheses raises a NameError.

Example: first class Animal: pass, then class Dog(Animal): pass. The child can access all public attributes and methods of the parent. You can also add new methods to the child; this gives the child specific behavior.

Practice Make Dog inherit from Animal

First define the Animal class; add a method def speak(self): and write print("Sound") in the body. Then define the child class with class Dog(Animal): pass. Finally create an instance with d = Dog() and call d.speak().

Starter code

main.py
# Define the Animal and Dog classes

Sample solution

main.py
# Define the Animal and Dog classes
class Animal:
    def speak(self):
        print("Sound")

class Dog(Animal):
    pass

d = Dog()
d.speak()

Expected output

Sound

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a valid inheritance definition?

  • class Dog -> Animal: pass
  • class Dog extends Animal: pass
  • class Dog(Animal): pass Correct answer
  • class Dog: Animal: pass

Explanation: In Python inheritance is written as class Child(Parent):.

2 Complete the inheritance definition

Question
class Dog(____):
    pass
Answer
class Dog(Animal):
    pass

Explanation: Dog inherits from Animal.

3 Match the inheritance parts

Term Meaning
Dog Child class
Animal Parent class
() Parentheses

All lessons in Intermediate