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

  • Variable Length Keyword Arguments in Python

    Variable Length Keyword Arguments in Python Variable length keyword arguments allow a function to accept any number of keyword arguments. This is done using the **kwargs syntax. Syntax python def function_name(**kwargs): # function body # kwargs becomes a dictionary containing all keyword arguments Simple Examples Example 1: Basic **kwargs python def print_info(**kwargs): print(“Information received:”, kwargs) print(“Type 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…

  • Inheritance in OOP Python: Rectangle & Cuboid Example

    Rectangle Inheritance in OOP Python: Rectangle & Cuboid Example Inheritance in object-oriented programming (OOP) allows a new class (the child class) to inherit properties and methods from an existing class (the parent class). This is a powerful concept for code reusability ♻️ and establishing a logical “is-a” relationship between classes. For instance, a Cuboid is…

  • Generators in Python

    Generators in Python What is a Generator? A generator is a special type of iterator that allows you to iterate over a sequence of values without storing them all in memory at once. Generators generate values on-the-fly (lazy evaluation) using the yield keyword. Key Characteristics Basic Syntax python def generator_function(): yield value1 yield value2 yield value3 Simple Examples Example…

  • Currency Converter

    Challenge: Currency Converter Class with Accessors & Mutators Objective: Create a CurrencyConverter class that converts an amount from a foreign currency to your local currency, using accessor and mutator methods. 1. Class Properties (Instance Variables) 2. Class Methods 3. Task Instructions

  • Special Sequences in Python

    Special Sequences in Python Regular Expressions – Detailed Explanation Special sequences are escape sequences that represent specific character types or positions in regex patterns. 1. \A – Start of String Anchor Description: Matches only at the absolute start of the string (unaffected by re.MULTILINE flag) Example 1: Match only at absolute beginning python import re text = “Start here\nStart…

Leave a Reply

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