Learn How to Code with Python: Beginner to Advanced Guide
Inheritance is a core mechanism in object-oriented programming that allows one class to derive behavior and structure from another. In Python, this is implemented by defining a child class that lists the parent class in parentheses. The child automatically gains access to the parent’s attributes and methods. This reduces duplication and centralizes shared logic in one place. A parent class, also called a base class or superclass, defines general behavior. A child class, also called a subclass, extends or modifies that behavior. The child can introduce new methods, override existing ones, or simply reuse them unchanged. This is a structural relationship: the child “is a” specialized version of the parent. For example, a generic `Animal` class might define methods like `eat()` or `sleep()`. A `Dog` class inheriting from `Animal` automatically gains those behaviors. It can then add `bark()` without rewriting `eat()` or `sleep()`. This separation keeps code modular and easier to maintain. Inheritance supports the principle of code reuse and hierarchical modeling. Instead of duplicating logic across multiple classes, you abstract shared behavior into a parent class. Every subclass then builds on that foundation, extending functionality in a controlled and predictable way. 1 It allows multiple functions to run simultaneously It enables code reuse and hierarchical modeling It increases execution speed automatically It prevents all runtime errors What is the main benefit of inheritance in Python? When defining a child class in Python, the syntax explicitly states the parent class in parentheses. For example: `class Dog(Animal):`. This establishes the inheritance relationship. If no parent is specified, the class implicitly inherits from `object`, the base of all classes in Python. The child class automatically gains access to the parent’s public and protected members. However, private members (those prefixed with double underscores) are name-mangled and not directly accessible. This enforces a degree of encapsulation while still enabling extension. If the child class does not override a method, Python resolves method calls using the Method Resolution Order (MRO). The MRO defines the order in which base classes are searched when executing a method. In single inheritance, the lookup moves from child to parent. Understanding this resolution order is critical when extending classes. If a method is not found in the child, Python searches upward. This predictable hierarchy prevents ambiguity in single inheritance scenarios. 1 The operating system The Method Resolution Order The import statement order The alphabetical order of classes What determines where Python looks for a method if it is not found in the child class? The `super()` function is a central tool when extending classes. It allows a child class to call methods from its parent class without directly referencing the parent’s name. This ensures maintainability and flexibility if the inheritance hierarchy changes. A common use case is in constructors. When a child class defines its own `__init__` method, it often needs to initialize the parent’s attributes. Using `super().__init__(...)` ensures that the parent’s initialization logic executes properly. Without calling `super()`, the parent’s constructor will not run automatically if the child defines its own constructor. This can result in missing attributes or incomplete initialization. Proper use of `super()` guarantees that inherited state is correctly established. In modern Python, calling `super()` without arguments is the recommended approach. It dynamically resolves the correct parent class according to the MRO. Hardcoding the parent class name is less flexible and more error-prone. 1 To delete parent attributes To initialize the parent class properly To prevent inheritance To speed up execution Why is `super()` commonly used in a child class constructor? Method overriding occurs when a child class defines a method with the same name as one in the parent class. The child’s version replaces the parent’s implementation for instances of the child class. This allows specialized behavior. For example, if a parent class `Shape` defines a method `area()` returning 0, a child class `Circle` can override `area()` to compute a real area based on radius. The child retains the method signature but changes the implementation. Overriding does not erase the parent method; it simply shadows it in the child’s context. The parent’s version can still be accessed using `super().method_name()` if needed. This allows extension rather than total replacement. This mechanism supports polymorphism. Different subclasses can implement the same method name with distinct behavior. Code operating on parent references can invoke methods without knowing the exact subclass type. 2 Deleting a method from the parent Renaming a method in the child Redefining a parent method in the child Importing a method from another module What is method overriding? Polymorphism enables different objects to respond to the same method call in different ways. When a function operates on a parent class reference, it can accept instances of any subclass. This is known as subtype polymorphism. For instance, a function that takes an `Animal` object and calls `make_sound()` can work with `Dog`, `Cat`, or `Bird` subclasses. Each subclass provides its own implementation of `make_sound()`. The power lies in abstraction. The calling code depends only on the parent interface, not on the specific subclass. This decouples systems and improves extensibility. New subclasses can be added without changing existing code. Polymorphism works naturally with inheritance. By extending a parent class and overriding methods, each subclass conforms to a shared contract while implementing its own behavior. 2 Encapsulation Compilation Polymorphism Iteration What allows different subclasses to respond differently to the same method call? A child class can extend a parent not only by overriding methods but also by adding entirely new methods. These new behaviors are exclusive to the subclass. They do not affect the parent class or other subclasses. For example, a `Vehicle` class may define `start()` and `stop()`. A `Car` subclass can add a method `open_trunk()`. Instances of `Car` can access both inherited and new methods. This extension maintains the integrity of the base class. The parent remains a general abstraction, while the child becomes more specific. The hierarchy reflects increasing specialization. This layered approach improves clarity. Instead of creating bloated base classes with every possible feature, you distribute responsibilities across subclasses logically. 1 The parent class gains the method Only the child class has access to it All classes lose inheritance The method overrides all parent methods What happens when a child class adds a new method? Multiple inheritance allows a class to inherit from more than one parent class. In Python, this is done by listing multiple base classes separated by commas. For example: `class Hybrid(Car, Electric):`. This feature can increase flexibility but also complexity. If two parent classes define the same method, Python resolves the conflict using the MRO. The order of inheritance in the class definition influences resolution. The MRO in multiple inheritance follows the C3 linearization algorithm. This ensures a consistent and predictable order. However, careless design can still create confusing hierarchies. Multiple inheritance should be used when a subclass truly represents a combination of distinct behaviors. Otherwise, composition—embedding objects instead of inheriting—may be more maintainable. 1 Random selection C3 linearization via MRO Manual user input Operating system rules What mechanism resolves method conflicts in multiple inheritance? Abstract base classes define methods that must be implemented by child classes. In Python, this is commonly done using the `abc` module. An abstract method has no concrete implementation in the base class. A subclass inheriting from an abstract base class must implement all abstract methods. If it fails to do so, Python prevents instantiation of that subclass. This enforces a contract. This approach is useful when designing frameworks or APIs. You define required behavior without specifying implementation details. Subclasses are forced to comply with the interface. Abstract classes strengthen architectural discipline. They ensure consistency across subclasses and prevent incomplete implementations from being instantiated. 1 It runs slower It cannot be instantiated It overrides the parent automatically It ignores the abstract methods What happens if a subclass does not implement all abstract methods? Encapsulation and inheritance are complementary but distinct. Encapsulation controls access to internal state, while inheritance promotes reuse and extension. A well-designed parent class exposes a stable interface. Private attributes in Python use double underscores and undergo name mangling. This prevents accidental access from subclasses. However, protected attributes (single underscore) are accessible but signal intended internal use. When extending classes, you should respect encapsulation boundaries. Direct manipulation of private parent attributes from a child class violates design principles. Instead, use provided methods. Maintaining this discipline preserves abstraction layers. The parent defines what is accessible; the child extends within those boundaries. 1 To increase speed To prevent accidental access from subclasses To enable multiple inheritance To remove attributes entirely What is the purpose of name mangling for private attributes? Inheritance should model logical relationships. The “is-a” test helps determine correctness. If a `Car` is a `Vehicle`, inheritance is appropriate. If a `Car` has an `Engine`, composition is usually better. Misusing inheritance leads to rigid hierarchies. Deep inheritance trees can become fragile and difficult to modify. Changes in the parent class can cascade through subclasses unexpectedly. Good design favors shallow hierarchies and clear abstractions. Inheritance is powerful but should not be used by default. Evaluate whether extension truly represents specialization. Strategic use of parent and child classes produces maintainable, extensible systems. Blindly stacking inheritance layers produces technical debt. 1 Use it in every case Apply the “is-a” relationship test Prefer deeper hierarchies Avoid parent classes entirely What is a guideline for deciding whether to use inheritance?