StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Polymorphism
Download
  1. Python
  2. Pyhton MCA (Machine Learning using Python)
  3. Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP
Abstraction
Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP

Polymorphism, which means "many forms," is a core principle in Object-Oriented Programming. It is the ability of different objects to respond to the same method call in their own unique, class-specific ways. It allows you to write generic, high-level code that can work with a variety of different objects without needing to know their exact type.

This principle is demonstrated perfectly in your selected code through the process_payment function.

How Polymorphism Works in Your Code

In your Canvas, both the CreditCard and PayPal classes inherit from the abstract PaymentMethod class. They both have a method called pay(), but each one implements this method differently:

  • The CreditCard class's pay() method prints a message about processing a card.

  • The PayPal class's pay() method prints a message about redirecting to PayPal.

The process_payment function is polymorphic. It doesn't care if the payment_method it receives is a CreditCard object or a PayPal object. It simply knows that it can call the .pay() method on whatever object it's given, and that object will know how to perform the action correctly for its specific type.

  • Use Case: To write flexible and decoupled code. The process_payment function can handle any new payment method you create in the future (like CryptoWallet or BankTransfer), as long as that new class also has a pay() method. The function doesn't need to be changed to support new types, which makes your code highly extensible.

Python

# --- Polymorphism in Action ---

 

# We have two different types of objects

credit_card = CreditCard("1111-2222-3333-4444")

paypal = PayPal("Rohit@example.com")

 

# We can treat them as the same "type" because they share a common interface (the .pay() method).

# This list contains objects of different classes.

payment_methods = [credit_card, paypal]

 

# We can loop through them and call the same method on each one.

# Each object responds in its own unique way. This is polymorphism.

for method in payment_methods:

    print("\nCalling .pay() on a new object...")

    method.pay(50.00)

Methods, Functions, and Operators

Polymorphism is a design principle, not a feature with its own specific methods or operators. It is achieved through a combination of:

1.   Inheritance: Having multiple classes inherit from a common parent.

2.   Method Overriding: Each child class provides its own specific implementation of a method defined in the parent.

The power of polymorphism is that it allows you to use standard functions and operators on a collection of different objects, and each object will respond appropriately. For example, the built-in len() function is polymorphic; it works on strings, lists, and dictionaries, and each object knows how to correctly report its own length.

 

Polymorphism is a core principle in Object-Oriented Programming that comes from the Greek words "poly" (meaning many) and "morph" (meaning form). At its heart, it is the idea that a single interface can represent different underlying forms (data types).

In simpler terms, it means you can write a single piece of code that can work with objects of different classes, as long as those classes share a common behavior (like having a method with the same name). The code doesn't need to know the exact class of the object it's dealing with; it just needs to know that the object can perform a certain action.


The Core Idea: Same Action, Different Behaviour

Think of a real-world example: the action "to speak."

  • A Dog object would perform the speak() action by printing "Woof!"

  • A Cat object would perform the speak() action by printing "Meow!"

  • A Duck object would perform the speak() action by printing "Quack!"

Polymorphism allows you to write a generic function that can take any of these animal objects and tell it to speak, without needing to check what kind of animal it is first.

Python

# A polymorphic function

def make_animal_speak(animal):

    # It doesn't care if 'animal' is a Dog, Cat, or Duck.

    # It just trusts that the object knows how to .speak().

    animal.speak()

This makes your code incredibly flexible and extensible. If you later create a Cow class with its own speak() method, the make_animal_speak function will work with it automatically, without any changes.


How Polymorphism is Achieved in Python

Python supports polymorphism in two main ways:

1.   Inheritance and Method Overriding (Classic OOP) This is when you have a parent class that defines a method, and several child classes inherit from it and provide their own specific implementations (overrides) of that method. This is a more formal way to ensure that different classes share a common interface.

2.   Duck Typing (More Pythonic) This is a more flexible and common approach in Python. The idea is summed up by the phrase: "If it walks like a duck and it quacks like a duck, then it must be a duck."

In Python, you don't need a formal inheritance structure to achieve polymorphism. As long as different objects have methods with the same name, you can use them interchangeably in your code. The code doesn't check the type of the object; it only checks if the object can perform the requested action (i.e., if it has the method you're trying to call).

The code example will demonstrate polymorphism.

# --- 1. Define Several Different Classes with a Common Interface ---

# These classes do NOT inherit from a common parent, but they all share

# a common method: .play(). This is an example of Duck Typing.

 

class AudioFile:

    """Represents a simple audio file."""

    def __init__(self, title, artist):

        self.title = title

        self.artist = artist

 

    def play(self):

        """The specific 'play' implementation for an audio file."""

        print(f"Playing audio: '{self.title}' by {self.artist}")

 

    def __str__(self):

        """String representation for this class."""

        return f"Audio: {self.title}"

 

class VideoFile:

    """Represents a simple video file."""

    def __init__(self, title, resolution):

        self.title = title

        self.resolution = resolution

 

    def play(self):

        """The specific 'play' implementation for a video file."""

        print(f"Playing video: '{self.title}' at {self.resolution}p resolution.")

 

    def __str__(self):

        """String representation for this class."""

        return f"Video: {self.title}"

 

class StreamedContent:

    """Represents content streamed from the internet."""

    def __init__(self, title, source_url):

        self.title = title

        self.source_url = source_url

 

    def play(self):

        """The specific 'play' implementation for streamed content."""

        print(f"Buffering from {self.source_url}...")

        print(f"Now streaming: '{self.title}'")

 

    def __str__(self):

        """String representation for this class."""

        return f"Stream: {self.title}"

 

# --- 2. Create a Generic Class that Uses These Objects ---

# This MediaPlayer class is polymorphic. It can work with any object

# that has a .play() method, without needing to know its specific class.

 

class MediaPlayer:

    """A media player that can play a playlist of various media types."""

    def __init__(self):

        self.playlist = []

 

    def add_to_playlist(self, media_item):

        """Adds any media item to the playlist."""

        self.playlist.append(media_item)

        print(f"Added '{media_item}' to the playlist.")

 

    def play_all(self):

        """Plays every item in the playlist."""

        print("\n--- Starting Playlist ---")

        if not self.playlist:

            print("Playlist is empty.")

            return

           

        for item in self.playlist:

            # This is the core of polymorphism.

            # The MediaPlayer doesn't care if 'item' is an AudioFile, VideoFile, or StreamedContent.

            # It just calls the .play() method, and the object itself knows how to perform the action correctly.

            item.play()

        print("--- Playlist Finished ---")

 

# --- 3. Demonstration ---

# Create instances of our different media classes.

song = AudioFile("Bohemian Rhapsody", "Queen")

movie = VideoFile("Inception", 1080)

live_stream = StreamedContent("Live News Broadcast", "news.com/live")

 

# Create a media player.

player = MediaPlayer()

 

# Add the different types of objects to the same playlist.

player.add_to_playlist(song)

player.add_to_playlist(movie)

player.add_to_playlist(live_stream)

 

# Play the entire playlist.

# Notice how the output is different for each item, even though we are calling the same .play() method.

player.play_all()

 

 

 

Abstraction
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website