0
0
PythonHow-ToBeginner · 4 min read

How to Use Inheritance in Python: Simple Guide with Examples

In Python, inheritance lets a class (child) use properties and methods from another class (parent) by specifying the parent class in parentheses after the child class name. This helps reuse code and create a hierarchy of classes easily.
📐

Syntax

Inheritance in Python is done by defining a new class with the parent class name inside parentheses. The child class inherits all methods and attributes from the parent.

  • ParentClass: The class you want to inherit from.
  • ChildClass(ParentClass): The new class that inherits from the parent.
python
class ParentClass:
    def parent_method(self):
        print("This is a method in the parent class.")

class ChildClass(ParentClass):
    pass
💻

Example

This example shows a parent class Animal with a method, and a child class Dog that inherits from Animal. The child can use the parent's method directly.

python
class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

class Cat(Animal):
    pass

my_dog = Dog()
my_cat = Cat()

my_dog.speak()  # Calls Dog's speak
my_cat.speak()  # Calls Animal's speak because Cat does not override it
Output
Dog barks Animal speaks
⚠️

Common Pitfalls

Common mistakes include forgetting to call the parent class's __init__ method when overriding it in the child, which can cause missing initialization. Also, not overriding methods when needed or misunderstanding method resolution order can cause unexpected behavior.

python
class Parent:
    def __init__(self):
        print("Parent init")

class Child(Parent):
    def __init__(self):
        print("Child init")  # Forgot to call super().__init__()

child = Child()  # Only prints 'Child init', parent init is skipped

# Correct way:
class ChildFixed(Parent):
    def __init__(self):
        super().__init__()  # Calls parent init
        print("ChildFixed init")

child_fixed = ChildFixed()
Output
Child init ChildFixed init Parent init
📊

Quick Reference

  • Use class Child(Parent): to inherit.
  • Override methods by defining them in the child class.
  • Call super().__init__() in child __init__ to run parent initialization.
  • Use inheritance to reuse code and create clear class hierarchies.

Key Takeaways

Inheritance lets a child class reuse code from a parent class by specifying it in parentheses.
Override parent methods in the child class to change behavior.
Always call super().__init__() in child __init__ to ensure proper initialization.
Inheritance helps organize code and avoid repetition.
Be mindful of method resolution order when multiple inheritance is involved.