Class Inheritance in Python

Level 4123 keystrokes

This shows class inheritance with method overriding, printing 'Woof!'. Dog inherits from Animal and overrides speak().

Python code

# Define a base class (parent class)
1class Animal:
# Default speak method for all animals
2 def speak(self):
3 return "..."
4
# Dog inherits from Animal (Animal in parentheses)
5class Dog(Animal):
# Override the speak method with dog-specific behavior
6 def speak(self):
7 return "Woof!"
8
# Create a Dog instance
9d = Dog()
# Call speak() - uses Dog's version, not Animal's
10print(d.speak())

Output

Woof!
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 6
  • )× 6
  • :× 4
  • .× 4
  • "× 4
  • !× 1
  • =× 1

More Python examples at level 4

← Python typing practice