8.7 Abstraction

8.7 Abstraction

Learning abstraction using Abstract Base Classes (ABCs) to create "contracts" that child classes must follow.

Abstraction is the process of simplifying complex systems by hiding unnecessary implementation details and exposing only the necessary functionalities to the user. In Python, abstraction is often achieved through Abstract Base Classes (ABCs) from the `abc` module. An abstract class defines a "contract" - a set of abstract methods (with the `@abstractmethod` decorator) that must be implemented by any child class. You cannot create an object directly from an abstract class.
from abc import ABC, abstractmethod

class Payment(ABC): # Abstract class
    @abstractmethod
    def process_payment(self, amount):
        pass

class CreditCardPayment(Payment):
    def process_payment(self, amount): # Implementation of the abstract method
        print(f"Processing ${amount} with a credit card.")

credit_payment = CreditCardPayment()
credit_payment.process_payment(100)

Practical Exercises

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.