Skip to content
PythonObject-Oriented Programmingbeginner25 min read

Inheritance and Method Overriding

Reuse class behavior through inheritance, customize inherited methods, and extend parent behavior safely with super().

In this lesson, you will learn

  • ✓Explain the difference between a base class and a subclass.
  • ✓Create a subclass using Python inheritance syntax.
  • ✓Identify which method Python calls when a method is inherited or overridden.
  • ✓Use super() to extend behavior defined by a parent class.
  • ✓Understand how inheritance interacts with __init__() and instance attributes.
  • ✓Recognize common inheritance mistakes and choose inheritance only when it makes the design clearer.

1. Understanding base classes and subclasses

Inheritance allows one class to acquire attributes and methods defined by another class. The existing class is called the base class or parent class. The class that inherits from it is called the derived class or subclass.

A subclass can use accessible methods inherited from its parent without defining those methods again. It can also introduce new methods and attributes of its own.

For example, Dog can inherit from Animal because a dog is a kind of animal. Animal contains behavior shared by animals, while Dog can contain behavior specific to dogs.

Python expresses this relationship by putting the parent class name inside parentheses after the subclass name: class Dog(Animal):. The parentheses identify the class from which Dog inherits.

Inheritance does not create a separate copy of the parent's source code inside the subclass. Python uses its method lookup rules to find the implementation to execute when an attribute or method is accessed.

Create a subclass and inherit a method

Create a subclass and inherit a method
python
class Animal:
def eat(self):
return 'Eating food'
 
class Dog(Animal):
pass
 
dog = Dog()
print(dog.eat())
Output
Eating food

class Animal: defines the parent class and its eat() method. class Dog(Animal): defines Dog as a subclass of Animal. The pass statement means that the Dog class has no additional statements in its body. It does not cancel inheritance. Dog() creates an instance of Dog. Python cannot find an eat() method defined directly in Dog, so it looks at Animal and finds the inherited method. The method returns 'Eating food', which print() displays.

Note

The parent class does not need to know about every subclass. Animal can define shared behavior without containing special code for Dog, Cat, or other future subclasses.

2. Method overriding and Python's method lookup

Method overriding occurs when a subclass defines a method with the same name as a method available in its parent class. When that method is called on an instance of the subclass, Python normally selects the subclass implementation first.

Overriding is useful when different subclasses should respond to the same operation in different ways. For example, Animal may provide a general speak() method, while Dog and Cat each provide their own version.

Python looks for an attribute or method through the class's method resolution order (MRO). In simple single inheritance, Python checks the subclass before its parent class. If the subclass defines the requested method, that implementation is selected.

Overriding does not delete the parent's method. The parent implementation remains available through the parent class and can also be called from an overriding method using super().

If a subclass does not override a method, it can inherit and use the parent's implementation unchanged.

Override a parent method

Override a parent method
python
class Animal:
def speak(self):
return 'Some sound'
 
class Dog(Animal):
def speak(self):
return 'Woof!'
 
class Cat(Animal):
def speak(self):
return 'Meow!'
 
print(Animal().speak())
print(Dog().speak())
print(Cat().speak())
Output
Some sound Woof! Meow!

Animal defines the original speak() implementation. Dog defines another speak() method with the same name, so a Dog instance uses the Dog implementation. Cat also overrides speak(), so a Cat instance uses the Cat implementation. The three objects support the same method call but can produce different results. This is a central benefit of overriding: related objects can share an interface while providing different behavior.

Note

A method's name alone does not determine which implementation runs. The type of the object and Python's method lookup order matter.

3. Using super() to reuse parent behavior

Sometimes a subclass should add behavior to a parent method instead of replacing all of its behavior. Python provides super() for this purpose.

In a normal single-inheritance example, super().method_name() calls the next applicable implementation of that method in the method resolution order. This lets the subclass reuse behavior rather than copying the parent's code.

For example, Animal may provide a general description of an animal. Dog can call super().describe() and add dog-specific information to the returned string.

Calling super() is different from creating a parent object. It does not construct another Animal instance. It provides a way to access the next implementation in the method resolution order for the current object.

Use super() when the parent's behavior is still useful. If the subclass should completely replace the inherited behavior, it can implement the method without calling super().

Extend a parent method with super()

Extend a parent method with super()
python
class Animal:
def describe(self):
return 'This is an animal.'
 
class Dog(Animal):
def describe(self):
parent_description = super().describe()
return parent_description + ' It is a dog.'
 
dog = Dog()
print(dog.describe())
Output
This is an animal. It is a dog.

Animal.describe() returns the general description. Dog.describe() overrides the inherited method. Inside Dog.describe(), super().describe() obtains the parent behavior through the next applicable implementation. The returned string is stored in parent_description. The subclass appends its own information and returns the combined string. print() displays the final string on one line.

Caution

Do not call super() automatically in every override. First decide whether the parent implementation should contribute to the result or perform part of the operation.

4. Inheritance and constructors (__init__)

The __init__() method initializes an instance after it is created. A parent class may define __init__() to initialize attributes shared by its subclasses.

If a subclass does not define its own __init__(), it can use the inherited initializer. This is often enough when the subclass needs no additional initialization.

If a subclass defines its own __init__(), it does not automatically execute the parent's __init__() just because the subclass inherits from that parent. When parent initialization is required, call super().__init__(...) explicitly.

Arguments passed to super().__init__() must match what the next initializer expects. Forgetting to initialize parent attributes can leave an object without state that its inherited methods rely on.

A subclass can initialize parent attributes through super().__init__() and then initialize its own additional attributes.

Inherit the parent's initializer

Inherit the parent's initializer
python
class Person:
def __init__(self, name):
self.name = name
 
def introduce(self):
return f'My name is {self.name}.'
 
class Student(Person):
pass
 
student = Student('Asha')
print(student.introduce())
Output
My name is Asha.

Person.__init__() receives the name argument and stores it in self.name. Student does not define __init__(), so it can use the inherited initializer. Student('Asha') initializes the Student instance with the name 'Asha'. The inherited introduce() method reads self.name and returns the formatted string.

Note

An inherited initializer is not the same as automatically running a parent initializer alongside a subclass initializer. When a subclass supplies its own __init__(), call super().__init__() if parent initialization is needed.

5. Practical design, limitations, and common mistakes

Inheritance is useful when several classes share a meaningful general concept and subclasses need to reuse or specialize that behavior. A Dog is an Animal, and a Student is a Person, so these are natural examples of inheritance.

Do not use inheritance merely to avoid writing a few repeated lines. If one object simply uses another object to complete a task, composition may be clearer. For example, a Car has an Engine; a car is not an engine.

A subclass should generally preserve the expectations of the parent class. If parent code promises a particular kind of result or behavior, a subclass should not unexpectedly violate that promise.

Python also supports multiple inheritance, in which a class can inherit from more than one parent. Python uses the method resolution order to determine which implementation is found first. Multiple inheritance is useful in some designs, but it introduces lookup rules that go beyond the simple single-inheritance examples in this lesson.

Inherited methods can access instance attributes through self. If a method expects an attribute that a subclass failed to initialize, calling the method may raise AttributeError.

A class can override a method but accidentally introduce incompatible parameters. For example, parent code may call a method with an argument that the subclass's version does not accept, causing a TypeError.

Good inheritance design keeps parent behavior general, subclass behavior focused, and overridden methods consistent with the intended interface.

A subclass can customize behavior and retain a shared interface

A subclass can customize behavior and retain a shared interface
python
class Shape:
def describe(self):
return 'I am a shape.'
 
class Circle(Shape):
def describe(self):
return 'I am a circle.'
 
class Square(Shape):
def describe(self):
return 'I am a square.'
 
shapes = [Circle(), Square()]
for shape in shapes:
print(shape.describe())
Output
I am a circle. I am a square.

Circle and Square both inherit from Shape. Each subclass overrides describe() with its own result. The loop calls describe() on each object without needing to check its class explicitly. Python selects the appropriate overridden method for each object. This is a simple example of polymorphism: the same method call can produce behavior specific to the object's class.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Writing class Dog: when Dog should inherit from Animal.

Why it happens: Inheritance is declared in the class header, for example class Dog(Animal):; omitting the base class means no inheritance from Animal.

Incorrect Approach
script.py
python
Writing class Dog: when Dog should inherit from Animal.
Correct Solution
script.py
python
Use class Dog(Animal): to declare the inheritance relationship.

Key takeaway: Use class Dog(Animal): to declare the inheritance relationship.

#2 Assuming a subclass automatically inherits every method implementation unchanged even when it overrides one.

Why it happens: A subclass inherits accessible behavior but can override a method, so method lookup uses the subclass implementation for that name.

Incorrect Approach
script.py
python
Assuming a subclass automatically inherits every method implementation unchanged even when it overrides one.
Correct Solution
script.py
python
Check whether the subclass defines the same method name. The subclass implementation is selected first in simple single inheritance.

Key takeaway: Check whether the subclass defines the same method name. The subclass implementation is selected first in simple single inheritance.

#3 Thinking that overriding deletes the parent method.

Why it happens: Overriding changes which implementation is selected for a call; the parent implementation remains available through an appropriate super() call or explicit base-class reference.

Incorrect Approach
script.py
python
Thinking that overriding deletes the parent method.
Correct Solution
script.py
python
The parent implementation still exists. Use super() when the overriding method needs the next applicable implementation.

Key takeaway: The parent implementation still exists. Use super() when the overriding method needs the next applicable implementation.

#4 Defining a subclass __init__() and assuming the parent __init__() runs automatically.

Why it happens: Python does not automatically call the parent initializer when a subclass defines its own __init__; call super().__init__(...) when parent initialization is required.

Incorrect Approach
script.py
python
Defining a subclass __init__() and assuming the parent __init__() runs automatically.
Correct Solution
script.py
python
Call super().__init__(...) explicitly when the parent initializer is needed.

Key takeaway: Call super().__init__(...) explicitly when the parent initializer is needed.

#5 Calling super() without checking the parent method's required arguments.

Why it happens: super() delegates to the next class in the method resolution order, so pass the arguments required by the relevant parent initializer or method.

Incorrect Approach
script.py
python
Calling super() without checking the parent method's required arguments.
Correct Solution
script.py
python
Pass the arguments expected by the next initializer or method implementation.

Key takeaway: Pass the arguments expected by the next initializer or method implementation.

#6 Using inheritance for an unrelated relationship just to reuse code.

Why it happens: Inheritance should model an is-a relationship; use composition or a helper function when the relationship is not genuinely hierarchical.

Incorrect Approach
script.py
python
Using inheritance for an unrelated relationship just to reuse code.
Correct Solution
script.py
python
Check whether the subclass genuinely is a more specific kind of the parent. Consider composition for a has-a relationship.

Key takeaway: Check whether the subclass genuinely is a more specific kind of the parent. Consider composition for a has-a relationship.

#7 Assuming an inherited method can use an attribute that was never initialized.

Why it happens: Inherited methods may depend on attributes normally created by an initializer, so ensure the required state exists before calling them.

Incorrect Approach
script.py
python
Assuming an inherited method can use an attribute that was never initialized.
Correct Solution
script.py
python
Ensure that every object has the attributes required by the methods it exposes.

Key takeaway: Ensure that every object has the attributes required by the methods it exposes.

#8 Changing an overridden method's parameters in a way that breaks code expecting the parent interface.

Why it happens: Overridden methods should preserve a compatible interface when callers expect the parent contract; changing required parameters can break substitutability.

Incorrect Approach
script.py
python
Changing an overridden method's parameters in a way that breaks code expecting the parent interface.
Correct Solution
script.py
python
Keep method behavior and accepted arguments compatible with the expectations of the base class.

Key takeaway: Keep method behavior and accepted arguments compatible with the expectations of the base class.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is inheritance in Python, and why is it useful?
Answer:
Inheritance allows a subclass to reuse attributes and methods defined by a base class. It reduces unnecessary duplication and provides a way to represent related classes. A subclass can also add new behavior or customize inherited behavior.
Q2:What is the difference between a parent class and a child class?
Answer:
A parent class, also called a base class, defines behavior that other classes can inherit. A child class, also called a subclass, inherits that behavior and can add or override methods and attributes.
Q3:What is method overriding?
Answer:
Method overriding occurs when a subclass defines a method with the same name as an inherited method. Python selects the subclass implementation first when that method is called on an instance of the subclass in a normal single-inheritance example.
Q4:What is the difference between inheritance and method overriding?
Answer:
Inheritance is the relationship that allows a subclass to reuse behavior from a parent class. Overriding is an optional technique within that relationship in which the subclass supplies its own implementation of an inherited method.
Q5:What does super() do?
Answer:
super() provides access to the next applicable implementation in the method resolution order. It is commonly used to reuse parent methods or initialize parent attributes without hard-coding a direct parent-class call.
Q6:Does Python automatically call the parent __init__() when a subclass defines its own __init__()?
Answer:
No. If the subclass defines its own initializer, the parent initializer does not automatically run just because of inheritance. The subclass should call super().__init__(...) when it needs the parent initialization.
Q7:Can a subclass inherit a method and also define its own methods?
Answer:
Yes. A subclass can inherit methods unchanged, override selected methods, and define additional methods specific to itself. It does not need to override every method in its parent.
Q8:What is the difference between inheritance and composition?
Answer:
Inheritance represents an is-a relationship, such as Dog being an Animal. Composition represents a has-a relationship, such as Car having an Engine. Composition can be a clearer choice when one object uses another object rather than being a specialized version of it.
Q9:What is polymorphism, and how does overriding support it?
Answer:
Polymorphism allows objects of different classes to respond to the same operation in different ways. For example, Dog and Cat can both provide speak(), but calling speak() returns different results depending on the object.
Q10:What is the method resolution order?
Answer:
The method resolution order, or MRO, is the order Python follows when searching classes for an attribute or method. In simple single inheritance, Python checks the subclass before its parent. The MRO is particularly important when multiple inheritance is used.

Key takeaways

  • Inheritance lets a subclass reuse methods and attributes defined by a base class.
  • A subclass can add new methods without overriding inherited methods.
  • Method overriding lets a subclass customize an inherited method.
  • Python checks the subclass before its parent in simple single inheritance.
  • super() accesses the next applicable implementation in the method resolution order.
  • When a subclass defines its own __init__(), call super().__init__(...) when parent initialization is needed.
  • Use inheritance for a genuine is-a relationship and consider composition for a has-a relationship.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: