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

  • Dynamically Typed vs. Statically Typed Languages 🔄↔️

    Dynamically Typed vs. Statically Typed Languages 🔄↔️ Dynamically Typed Languages 🚀 Python Pros: Cons: Statically Typed Languages 🔒 Java Pros: Cons: Key Differences 🆚 Feature Dynamically Typed Statically Typed Type Checking Runtime Compile-time Variable Types Can change during execution Fixed after declaration Error Detection Runtime exceptions Compile-time failures Speed Slower (runtime checks) Faster (optimized binaries)…

  • Class06,07 Operators, Expressions

    In Python, operators are special symbols that perform operations on variables and values. They are categorized based on their functionality: ⚙️ 1. Arithmetic Operators ➕➖✖️➗ Used for mathematical operations: Python 2. Assignment Operators ➡️ Assign values to variables (often combined with arithmetic): Python 3. Comparison Operators ⚖️ Compare values → return True or False: Python…

  • 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}”,…

  • For loop 13 and 14th class

    The range() Function in Python The range() function is a built-in Python function that generates a sequence of numbers. It’s commonly used in for loops to iterate a specific number of times. Basic Syntax There are three ways to use range(): 1. range(stop) – One Parameter Form Generates numbers from 0 up to (but not including) the stop value. python for i in range(5):…

  •  index(), count(), reverse(), sort()

    Python List Methods: index(), count(), reverse(), sort() Let’s explore these essential list methods with multiple examples for each. 1. index() Method Returns the index of the first occurrence of a value. Examples: python # Example 1: Basic usage fruits = [‘apple’, ‘banana’, ‘cherry’, ‘banana’] print(fruits.index(‘banana’)) # Output: 1 # Example 2: With start parameter print(fruits.index(‘banana’, 2)) # Output: 3 (starts searching…

  • Formatted printing

    C-Style String Formatting in Python Python supports C-style string formatting using the % operator, which provides similar functionality to C’s printf() function. This method is sometimes called “old-style” string formatting but remains useful in many scenarios. Basic Syntax python “format string” % (values) Control Characters (Format Specifiers) Format Specifier Description Example Output %s String “%s” % “hello” hello %d…

Leave a Reply

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