Overriding Parent Class Methods and Handling Return Values in Python

In object-oriented programmnig, subclassing allows you to override parent class methods. When overriding, it's crucial to handle return values appropriately if the parent method provides one. For example, consider a custom process class derived from Ptyhon's multiprocessing.Process:

import os
import time
from multiprocessing import Process


class CustomProcess(Process):
    def __init__(self, identifier):
        super().__init__()
        self.identifier = identifier

    def run(self):
        pid = os.getpid()
        print(f'Process PID: {pid}')
        print(f'Process {self.identifier} executed')

    def start(self):
        print(f'Process {self.identifier} starting')
        super().start()

    def terminate(self):
        super().terminate()

    def join(self, timeout=None):
        super().join()

    def is_alive(self):
        # Override without returning the parent's value
        super().is_alive()


if __name__ == '__main__':
    processes = []
    for idx in range(5):
        proc = CustomProcess(idx)
        proc.start()
        print(proc.is_alive())
        processes.append(proc)
    for proc in processes:
        print(proc.is_alive())
        print(f'Terminating process {proc}')
        proc.terminate()
        time.sleep(0.2)
        print(proc.is_alive())
        proc.join()
        print(proc.is_alive())

Running this code prints None for each is_alive() call because the overridden method doesn't return the boolean value from the parent's is_alive(). The parent class method in multiprocessing.Process returns True or False:

def is_alive(self):
    return False  # Simplified representation

To preserve the return value, explicitly capture and return it in the subclass:

def is_alive(self):
    status = super().is_alive()
    return status

A more robust implementation includes error handling:

def is_alive(self):
    try:
        return super().is_alive()
    except Exception as e:
        print(f'Error checking process status: {e}')
        return False

This ensures the subclass method behaves like the parent, returning the liveness status while adding custom logic if needed.

Tags: python multiprocessing Inheritance method-overriding object-oriented-programming

Posted on Thu, 25 Jun 2026 16:26:06 +0000 by EchoFool