StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Abstraction
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
Encapsulation : Polymorphism
Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP

Abstraction is a core principle in Object-Oriented Programming (OOP) that focuses on hiding complex implementation details while exposing only the essential, high-level functionalities to the user. The goal is to create a simple and clear interface for interacting with an object, without needing to know the intricate logic happening behind the scenes.

Think of it as a blueprint. An abstract class can define a set of methods that must be implemented by any child class that inherits from it, but it doesn't say how they should be implemented. This enforces a common structure across different but related classes.

How Abstraction is Implemented in Python

Python achieves abstraction using the abc (Abstract Base Classes) module. The key components are:

  • ABC (Abstract Base Class): A class that inherits from ABC becomes an abstract class. You cannot create an instance of an abstract class directly. It's meant to be a template for other classes.

  • @abstractmethod decorator: This decorator is used to declare a method as an abstract method. An abstract method has a declaration in the parent abstract class but no implementation (it just has pass). Any child class that inherits from the abstract class must provide its own implementation for this method, or it will raise an error.


Use Case: Defining a Common Interface for Different Payment Methods

Imagine you are building an e-commerce system. You need to process payments, but you want to support multiple payment methods like Credit Card, PayPal, and UPI. Each method has a different way of processing a payment, but they all share the same essential action: a pay() method. Abstraction is perfect for this.

You can create an abstract PaymentMethod class with an abstract pay() method. This ensures that any new payment method you add in the future (like CryptoWallet) is guaranteed to have a pay() method, making your system consistent and predictable.

I have provide a code for you that contains the detailed code for this example.

# --- 1. Import the necessary tools from the 'abc' module ---

from abc import ABC, abstractmethod

 

# --- 2. Define the Abstract Base Class (ABC) ---

# This class acts as a blueprint and cannot be instantiated directly.

class PaymentMethod(ABC):

    """

    An abstract base class that defines the interface for all payment methods.

    Any class that inherits from this MUST implement the 'pay' method.

    """

 

    @abstractmethod

    def pay(self, amount):

        """

        This is an abstract method. It has no implementation here.

        Subclasses are required to provide their own version of this method.

        """

        pass

 

# --- 3. Create Concrete Subclasses ---

# These are usable classes that inherit from the abstract class and provide

# the required implementation for the abstract methods.

 

class CreditCard(PaymentMethod):

    """A concrete class for processing credit card payments."""

 

    def __init__(self, card_number):

        self.card_number = card_number

 

    def pay(self, amount):

        """

        The specific implementation of the 'pay' method for credit cards.

        """

        print(f"Processing credit card payment of ${amount:.2f} with card ending in {self.card_number[-4:]}...")

        # In a real application, this would involve complex logic to connect to a payment gateway.

        print("Payment successful.")

 

class PayPal(PaymentMethod):

    """A concrete class for processing PayPal payments."""

 

    def __init__(self, email_address):

        self.email_address = email_address

 

    def pay(self, amount):

        """

        The specific implementation of the 'pay' method for PayPal.

        """

        print(f"Redirecting to PayPal for a payment of ${amount:.2f} from {self.email_address}...")

        # Real-world logic to interact with the PayPal API would go here.

        print("Payment successful.")

 

# --- 4. Using the Concrete Classes ---

# We can create instances of the concrete classes.

credit_card_payment = CreditCard("1234-5678-9012-3456")

paypal_payment = PayPal("user@example.com")

 

# We can call the 'pay' method on each object, and it will execute the

# specific implementation for that class. This is also an example of Polymorphism.

print("--- Processing Payments ---")

credit_card_payment.pay(100.50)

print("-" * 20)

paypal_payment.pay(75.00)

 

# --- 5. Abstraction in Action ---

# You CANNOT create an instance of the abstract class itself.

# The following line would raise a TypeError if uncommented:

# invalid_payment = PaymentMethod()

 

# The abstraction ensures that any object that claims to be a 'PaymentMethod'

# is guaranteed to have a working '.pay()' method, which makes our code reliable.

def process_payment(payment_method, amount):

    """

    This function can process any payment method, as long as it adheres

    to the PaymentMethod blueprint (i.e., has a .pay() method).

    """

    print("\n--- Using a generic payment processing function ---")

    payment_method.pay(amount)

 

# We can pass different types of payment objects to the same function.

process_payment(credit_card_payment, 50.00)

process_payment(paypal_payment, 25.00)

 

 

Encapsulation Polymorphism
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