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

  • re.findall()

    Python re.findall() Method Explained The re.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings or tuples. Syntax python re.findall(pattern, string, flags=0) Key Characteristics: Example 1: Extracting All Numbers from Text python import retext = “I bought 5 apples for $3.50, 2 bananas for $1.25, and 10 oranges for $7.80.”result = re.findall(r”\d{3}”,…

  • group() and groups()

    Python re group() and groups() Methods Explained The group() and groups() methods are used with match objects to extract captured groups from regex patterns. They work on the result of re.search(), re.match(), or re.finditer(). group() Method groups() Method Example 1: Basic Group Extraction python import retext = “John Doe, age 30, email: john.doe@email.com”# Pattern with multiple capture groupspattern = r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’///The Pattern: r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’Breakdown by Capture…

  • Mathematical Functions

    1. abs() Syntax: abs(x)Description: Returns the absolute value (non-negative value) of a number. Examples: python # 1. Basic negative numbers print(abs(-10)) # 10 # 2. Positive numbers remain unchanged print(abs(5.5)) # 5.5 # 3. Floating point negative numbers print(abs(-3.14)) # 3.14 # 4. Zero remains zero print(abs(0)) # 0 # 5. Complex numbers (returns magnitude) print(abs(3 +…

  • Operator Overloading

    Operator Overloading in Python with Simple Examples Operator overloading allows you to define how Python operators (like +, -, *, etc.) work with your custom classes. This makes your objects behave more like built-in types. 1. What is Operator Overloading? 2. Basic Syntax python class ClassName: def __special_method__(self, other): # Define custom behavior 3. Common Operator Overloading Methods Operator…

  • Python Program to Check Pangram Phrases

    Python Program to Check Pangram Phrases What is a Pangram? A pangram is a sentence or phrase that contains every letter of the alphabet at least once. Method 1: Using Set Operations python def is_pangram_set(phrase): “”” Check if a phrase is a pangram using set operations “”” # Convert to lowercase and remove non-alphabetic characters…

  • re.fullmatch() Method

    Python re.fullmatch() Method Explained The re.fullmatch() method checks if the entire string matches the regular expression pattern. It returns a match object if the whole string matches, or None if it doesn’t. Syntax python re.fullmatch(pattern, string, flags=0) import re # Target string string = “The Euro STOXX 600 index, which tracks all stock markets across Europe including the FTSE, fell by…

Leave a Reply

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