Method overriding

Method overriding is a key feature of object-oriented programming (OOP) and inheritance. It allows a subclass (child class) to provide its own specific implementation of a method that is already defined in its superclass (parent class).

When a method is called on an object of the child class, the child’s version of the method is executed instead of the parent’s version.


Simple Example 🐾

Let’s consider a parent class Animal with a method speak(). Different animals make different sounds, so we can create child classes like Dog and Cat that override the generic speak() method.

Python

# 1. Parent Class (Superclass)
class Animal:
    def speak(self):
        print("The animal makes a sound.")

# 2. Child Class (Subclass) that inherits from Animal
class Dog(Animal):
    # Overriding the parent's speak() method
    def speak(self):
        print("The dog barks: Woof! 🐶")

# 3. Another Child Class
class Cat(Animal):
    # Overriding the parent's speak() method
    def speak(self):
        print("The cat meows: Meow! 🐱")

# --- Let's see it in action ---

# Create objects (instances) of each class
generic_animal = Animal()
my_dog = Dog()
my_cat = Cat()

# Call the speak() method on each object
generic_animal.speak()  # Calls the method from the Animal class
my_dog.speak()          # Calls the overridden method from the Dog class
my_cat.speak()          # Calls the overridden method from the Cat class

Output:

The animal makes a sound.
The dog barks: Woof! 🐶
The cat meows: Meow! 🐱

Here, Dog and Cat both provide their own versions of speak(), which is why they produce different outputs than the base Animal class.


Extending a Method with super()

Sometimes you don’t want to completely replace the parent’s method but just add more functionality to it. You can do this using the super() function, which allows you to call the parent class’s method from within the child class.

Example:

Python

class Person:
    def __init__(self, name):
        self.name = name

    def work(self):
        print(f"{self.name} starts working.")

class SoftwareDeveloper(Person):
    def work(self):
        # First, call the work() method from the parent (Person) class
        super().work()
        # Then, add the specific functionality for this child class
        print(f"{self.name} writes code. 💻")

# --- Let's see it in action ---
dev = SoftwareDeveloper("Alice")
dev.work()

Output:

Alice starts working.
Alice writes code. 💻

In this case, the SoftwareDeveloper‘s work() method extends the Person‘s work() method instead of completely replacing it.

“మెథడ్ ఓవర్‌రైడింగ్” గురించిన వివరణను తెలుగులో కింద ఇచ్చాను.

మెథడ్ ఓవర్‌రైడింగ్ (Method Overriding) అనేది ఆబ్జెక్ట్-ఓరియెంటెడ్ ప్రోగ్రామింగ్ (OOP) మరియు ఇన్హెరిటెన్స్ (Inheritance) యొక్క ఒక ముఖ్యమైన లక్షణం. ఇది ఒక సబ్‌క్లాస్ (చైల్డ్ క్లాస్) తన సూపర్‌క్లాస్ (పేరెంట్ క్లాస్)లో ఇప్పటికే డిఫైన్ చేయబడిన ఒక మెథడ్‌కు తన స్వంత నిర్దిష్టమైన ఇంప్లిమెంటేషన్‌ను అందించడానికి అనుమతిస్తుంది.

చైల్డ్ క్లాస్ యొక్క ఆబ్జెక్ట్‌పై ఒక మెథడ్ కాల్ చేయబడినప్పుడు, పేరెంట్ వెర్షన్‌కు బదులుగా చైల్డ్ యొక్క వెర్షన్ మెథడ్ ఎగ్జిక్యూట్ అవుతుంది.


సాధారణ ఉదాహరణ 🐾

speak() అనే మెథడ్ ఉన్న Animal అనే పేరెంట్ క్లాస్‌ను పరిగణిద్దాం. వేర్వేరు జంతువులు వేర్వేరు శబ్దాలు చేస్తాయి, కాబట్టి మనం Dog మరియు Cat వంటి చైల్డ్ క్లాస్‌లను సృష్టించి, సాధారణ speak() మెథడ్‌ను ఓవర్‌రైడ్ చేయవచ్చు.

Python

# 1. పేరెంట్ క్లాస్ (సూపర్‌క్లాస్)
class Animal:
    def speak(self):
        print("జంతువు ఒక శబ్దం చేస్తుంది.")

# 2. Animal నుండి ఇన్హెరిట్ చేసుకునే చైల్డ్ క్లాస్ (సబ్‌క్లాస్)
class Dog(Animal):
    # పేరెంట్ యొక్క speak() మెథడ్‌ను ఓవర్‌రైడ్ చేయడం
    def speak(self):
        print("కుక్క మొరుగుతుంది: భౌ! భౌ! 🐶")

# 3. మరొక చైల్డ్ క్లాస్
class Cat(Animal):
    # పేరెంట్ యొక్క speak() మెథడ్‌ను ఓవర్‌రైడ్ చేయడం
    def speak(self):
        print("పిల్లి అరుస్తుంది: మ్యావ్! 🐱")

# --- ఇది ఎలా పనిచేస్తుందో చూద్దాం ---

# ప్రతి క్లాస్ యొక్క ఆబ్జెక్ట్‌లను (ఇన్‌స్టాన్స్‌లను) క్రియేట్ చేయండి
generic_animal = Animal()
my_dog = Dog()
my_cat = Cat()

# ప్రతి ఆబ్జెక్ట్‌పై speak() మెథడ్‌ను కాల్ చేయండి
generic_animal.speak()  # Animal క్లాస్ నుండి మెథడ్‌ను కాల్ చేస్తుంది
my_dog.speak()          # Dog క్లాస్ నుండి ఓవర్‌రైడ్ చేయబడిన మెథడ్‌ను కాల్ చేస్తుంది
my_cat.speak()          # Cat క్లాస్ నుండి ఓవర్‌రైడ్ చేయబడిన మెథడ్‌ను కాల్ చేస్తుంది

ఫలితం (Output):

జంతువు ఒక శబ్దం చేస్తుంది.
కుక్క మొరుగుతుంది: భౌ! భౌ! 🐶
పిల్లి అరుస్తుంది: మ్యావ్! 🐱

ఇక్కడ, Dog మరియు Cat రెండూ speak() యొక్క సొంత వెర్షన్లను అందిస్తాయి, అందుకే అవి బేస్ Animal క్లాస్ కంటే భిన్నమైన అవుట్‌పుట్‌లను ఇస్తాయి.


super() తో మెథడ్‌ను విస్తరించడం

కొన్నిసార్లు మీరు పేరెంట్ మెథడ్‌ను పూర్తిగా భర్తీ చేయకుండా, దానికి మరికొంత కార్యాచరణను జోడించాలనుకోవచ్చు. super() ఫంక్షన్‌ను ఉపయోగించి మీరు దీన్ని చేయవచ్చు, ఇది చైల్డ్ క్లాస్‌లో இருந்து పేరెంట్ క్లాస్ యొక్క మెథడ్‌ను కాల్ చేయడానికి మిమ్మల్ని అనుమతిస్తుంది.

ఉదాహరణ:

Python

class Person:
    def __init__(self, name):
        self.name = name

    def work(self):
        print(f"{self.name} పని చేయడం ప్రారంభిస్తారు.")

class SoftwareDeveloper(Person):
    def work(self):
        # మొదట, పేరెంట్ (Person) క్లాస్ నుండి work() మెథడ్‌ను కాల్ చేయండి
        super().work()
        # ఆ తర్వాత, ఈ చైల్డ్ క్లాస్ కోసం ప్రత్యేక కార్యాచరణను జోడించండి
        print(f"{self.name} కోడ్ వ్రాస్తారు. 💻")

# --- ఇది ఎలా పనిచేస్తుందో చూద్దాం ---
dev = SoftwareDeveloper("ఆలిస్")
dev.work()

ఫలితం (Output):

ఆలిస్ పని చేయడం ప్రారంభిస్తారు.
ఆలిస్ కోడ్ వ్రాస్తారు. 💻

ఈ సందర్భంలో, SoftwareDeveloper యొక్క work() మెథడ్, Person యొక్క work() మెథడ్‌ను పూర్తిగా భర్తీ చేయడానికి బదులుగా దానిని విస్తరిస్తుంది.

Similar Posts

  • Special Character Classes Explained with Examples

    Special Character Classes Explained with Examples 1. [\\\^\-\]] – Escaped special characters in brackets Description: Matches literal backslash, caret, hyphen, or closing bracket characters inside character classes Example 1: Matching literal special characters python import re text = “Special chars: \\ ^ – ] [” result = re.findall(r'[\\\^\-\]]’, text) print(result) # [‘\\’, ‘^’, ‘-‘, ‘]’] # Matches…

  • Strings in Python Indexing,Traversal

    Strings in Python and Indexing Strings in Python are sequences of characters enclosed in single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ or “”” “””). They are immutable sequences of Unicode code points used to represent text. String Characteristics Creating Strings python single_quoted = ‘Hello’ double_quoted = “World” triple_quoted = ”’This is…

  • Python Input Function: A Beginner’s Guide with Examples

    The input() function in Python is used to take user input from the keyboard. It allows your program to interact with the user by prompting them to enter data, which can then be used in your code. By default, the input() function returns the user’s input as a string. Syntax of input() python Copy input(prompt) Key Points About input() Basic Examples of input() Example…

  • Python Statistics Module

    Python Statistics Module: Complete Methods Guide with Examples Here’s a detailed explanation of each method in the Python statistics module with 3 practical examples for each: 1. Measures of Central Tendency mean() – Arithmetic Average python import statistics as stats # Example 1: Basic mean calculation data1 = [1, 2, 3, 4, 5] result1 = stats.mean(data1) print(f”Mean of…

  • Quantifiers (Repetition)

    Quantifiers (Repetition) in Python Regular Expressions – Detailed Explanation Basic Quantifiers 1. * – 0 or more occurrences (Greedy) Description: Matches the preceding element zero or more times Example 1: Match zero or more digits python import re text = “123 4567 89″ result = re.findall(r’\d*’, text) print(result) # [‘123’, ”, ‘4567’, ”, ’89’, ”] # Matches…

  • Indexing and Slicing in Python Lists Read

    Indexing and Slicing in Python Lists Read Indexing and slicing are fundamental operations to access and extract elements from a list in Python. 1. Indexing (Accessing Single Elements) Example 1: Basic Indexing python fruits = [“apple”, “banana”, “cherry”, “date”, “fig”] # Positive indexing print(fruits[0]) # “apple” (1st element) print(fruits[2]) # “cherry” (3rd element) # Negative indexing print(fruits[-1]) # “fig”…

Leave a Reply

Your email address will not be published. Required fields are marked *