0% found this document useful (0 votes)
12 views4 pages

Abstraction in Python

Uploaded by

Bandari Ganesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
12 views4 pages

Abstraction in Python

Uploaded by

Bandari Ganesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 4

Abstraction in Python is a core concept in Object-Oriented Programming (OOP) that focuses on

hiding the implementation details and exposing only essential features to the users. Abstraction
allows programmers to manage complexity by breaking down a large system into smaller,
manageable parts, and hiding unnecessary details to reduce confusion. In Python, abstraction is
implemented primarily through Abstract Classes and Interfaces using the abc module.

Here are the key concepts covered in Abstraction in Python:

1. Abstract Classes
Definition: An abstract class in Python is a class that contains one or more abstract methods.
Abstract methods are methods that are declared, but contain no implementation, and must be
implemented by any concrete (non-abstract) subclass.
Purpose: Abstract classes are used to provide a blueprint for other classes. They allow you to
define methods that must be created in any child class but leave the implementation details to
the subclasses.
Example:

python Copy code

from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def


sound(self): pass # Abstract method class Dog(Animal): def sound(self): return
"Bark" class Cat(Animal): def sound(self): return "Meow" # dog = Animal() # This
would raise an error because Animal is abstract dog = Dog() print(dog.sound()) #
Output: Bark

2. Abstract Methods
Definition: An abstract method is a method that is declared within an abstract class but does
not have any implementation. Subclasses are forced to provide a concrete implementation of
the abstract method.
Purpose: It ensures that subclasses provide specific functionality by implementing these
methods, enforcing certain behaviors.
Example:

python Copy code

class Vehicle(ABC): @abstractmethod def start_engine(self): pass class


Car(Vehicle): def start_engine(self): return "Car engine started" my_car = Car()
print(my_car.start_engine()) # Output: Car engine started

3. Partial Abstraction
Definition: Abstract classes in Python can also have concrete methods in addition to abstract
methods. This is called partial abstraction, where some methods are implemented, and others
are left for the subclass to implement.
Purpose: This allows the abstract class to provide a default behavior while still enforcing certain
methods to be overridden.
Example:

python Copy code

class Appliance(ABC): def plug_in(self): print("Plugged in") # Concrete method


@abstractmethod def turn_on(self): pass class WashingMachine(Appliance): def
turn_on(self): print("Washing machine is now on") wm = WashingMachine()
wm.plug_in() # Output: Plugged in wm.turn_on() # Output: Washing machine is now on

4. Interfaces (Using Abstraction)


Definition: An interface is a fully abstract class in Python where all methods are abstract and
must be implemented by the subclass. Python doesn’t have interfaces as a separate concept
like Java, but abstract classes with all methods abstract can act as interfaces.
Purpose: This enforces that the subclass implements every method of the abstract class,
ensuring a particular structure.
Example:

python Copy code

class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def


perimeter(self): pass class Rectangle(Shape): def __init__(self, width, height):
self.width = width self.height = height def area(self): return self.width *
self.height def perimeter(self): return 2 * (self.width + self.height) rect =
Rectangle(10, 20) print(rect.area()) # Output: 200 print(rect.perimeter()) #
Output: 60

5. Encapsulation and Abstraction


Relationship: Abstraction and Encapsulation are closely related but distinct concepts.

Encapsulation: Refers to the bundling of data and methods that operate on the data,
restricting direct access to some of the object’s components (private/protected members).
Abstraction: Focuses on hiding the complexity of implementation and exposing only the
necessary parts.
Example: Encapsulation involves controlling access to certain components, while abstraction
hides the complexities by only exposing relevant methods to the user.

6. Hiding Implementation Details


Definition: Abstraction allows users to focus on "what" the object does rather than "how" it
does it. By abstracting away the implementation details, users can interact with complex
systems in a simplified manner.
Purpose: It improves code maintainability and reduces the cognitive load on the user by hiding
complex logic behind simple interfaces.
Example:

python Copy code

class PaymentSystem(ABC): @abstractmethod def process_payment(self, amount): pass


class PayPal(PaymentSystem): def process_payment(self, amount): print(f"Processing
payment of {amount} via PayPal") class Stripe(PaymentSystem): def
process_payment(self, amount): print(f"Processing payment of {amount} via Stripe")
# The user doesn't need to know the internal implementation details payment =
PayPal() payment.process_payment(100) # Output: Processing payment of 100 via
PayPal

7. Loose Coupling through Abstraction


Definition: Abstraction leads to loose coupling between components in a system. By using
abstract classes, you can create loosely coupled systems where classes are not tightly
dependent on each other’s implementations.
Example: In the example above, the PaymentSystem class allows you to easily switch
between PayPal , Stripe , or any other payment processor without changing the client code.

8. Advantages of Abstraction
Modularity: Abstraction helps in breaking down large, complex systems into smaller,
manageable units. Each class focuses on one thing.
Maintainability: Since the implementation details are hidden, changes in the internal logic
don’t affect the external usage of the system.
Reusability: Abstract classes provide a reusable interface that can be inherited by multiple
classes.
Security: By hiding sensitive or unnecessary details, abstraction can also improve security.
Ease of Use: Users can interact with a system without worrying about the complex
implementation details.

9. Real-World Examples of Abstraction


File Handling: In Python, you don't need to know how file reading or writing works internally.
You just call the open() , read() , or write() methods to perform the necessary actions.

python Copy code

with open('file.txt', 'r') as file: content = file.read() print(content)

Database Handling: Abstraction in database libraries allows you to execute queries without
knowing how the connection or query execution is handled internally.

python Copy code


# SQLAlchemy (abstracts database interaction)
session.query(User).filter_by(name='Kapil').first()

Summary of Key Concepts:


1. Abstract Classes: Define common interfaces but hide implementation details.
2. Abstract Methods: Enforce subclasses to provide specific implementations.
3. Partial Abstraction: Abstract classes can have both abstract and concrete methods.
4. Interfaces: Fully abstract classes used as contracts for subclasses.
5. Encapsulation vs Abstraction: Encapsulation controls access, while abstraction hides
implementation complexity.
6. Loose Coupling: Abstraction reduces dependency between components, leading to a flexible
system.
7. Hiding Implementation: Focuses on exposing essential features and hiding unnecessary
complexities.

Abstraction simplifies coding by focusing on "what" a system should do rather than "how" it
achieves it, making code cleaner, more maintainable, and user-friendly.

You might also like