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
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
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
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
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()
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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?
Q2:What is the difference between a parent class and a child class?
Q3:What is method overriding?
Q4:What is the difference between inheritance and method overriding?
Q5:What does super() do?
Q6:Does Python automatically call the parent __init__() when a subclass defines its own __init__()?
Q7:Can a subclass inherit a method and also define its own methods?
Q8:What is the difference between inheritance and composition?
Q9:What is polymorphism, and how does overriding support it?
Q10:What is the method resolution order?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: