Introduction π
**Abstraction** in Object-Oriented Programming (OOP) is the concept of hiding unnecessary implementation details and showing only the essential features to the user. Python provides abstraction mainly through **abstract classes** and **abstract methods** using theabc (Abstract Base Class) module.
Note
Implementation = *How it does* (hidden) π
1. Real-Life Example of Abstraction π
When you drive a car, you use a steering wheel, pedals, etc., but you don't need to understand how the engine works internally. This is **abstraction** β exposing essential features, hiding complexity.
2. Abstraction in Python Using Abstract Classes π§±
Python allows you to create abstract classes using ABC and @abstractmethod.
abstract_basic.py
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Bark"
d = Dog()
print(d.sound())β Animal is an abstract class
β sound() is an abstract method
β Any subclass **must** implement the abstract method
3. Why Use Abstraction? π€
- β Hides unnecessary details
- β Provides a clear structure for subclasses
- β Enforces method implementation
- β Makes code cleaner and more maintainable
- β Helps build large applications with rules & consistency
4. Abstract Class Cannot Be Instantiated β
cannot_instantiate.py
a = Animal() # β Error: Can't instantiate abstract classNote
5. Example with Multiple Abstract Methods π§©
multiple_abstract_methods.py
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self): pass
@abstractmethod
def stop(self): pass
class Car(Vehicle):
def start(self):
print("Car started")
def stop(self):
print("Car stopped")
c = Car()
c.start()
c.stop()β Every abstract method must be implemented by the child class.
6. Abstract Class with Constructor π―
abstract_constructor.py
from abc import ABC, abstractmethod
class Shape(ABC):
def __init__(self, color):
self.color = color
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, side, color):
super().__init__(color)
self.side = side
def area(self):
return self.side ** 2
s = Square(5, "blue")
print(s.area())β Abstract classes can have constructors
β Child classes must call them using super()
7. Example: Payment System π³
payment_example.py
from abc import ABC, abstractmethod
class Payment(ABC):
@abstractmethod
def pay(self, amount): pass
class CashPayment(Payment):
def pay(self, amount):
print(f"Paid {amount} in cash")
class CardPayment(Payment):
def pay(self, amount):
print(f"Paid {amount} via card")
p = CardPayment()
p.pay(500)8. Partially Abstract Classes (Concrete + Abstract Methods) β‘
partial_abstract.py
from abc import ABC, abstractmethod
class Device(ABC):
def power_on(self):
print("Device is ON")
@abstractmethod
def run(self):
pass
class Laptop(Device):
def run(self):
print("Laptop running...")
l = Laptop()
l.power_on()
l.run()Note
9. Using Abstraction for Enforcing Rules π‘οΈ
enforced_rules.py
from abc import ABC, abstractmethod
class Database(ABC):
@abstractmethod
def connect(self): pass
@abstractmethod
def disconnect(self): pass
class MySQL(Database):
def connect(self):
print("Connected to MySQL")
def disconnect(self):
print("Disconnected from MySQL")
db = MySQL()
db.connect()
db.disconnect()10. Abstraction vs Encapsulation βοΈ
| Abstraction | Encapsulation |
|---|---|
| Shows essential features only | Hides data using private/protected members |
| Achieved using abstract classes/methods | Achieved using getters/setters |
| Focuses on βWhat?β | Focuses on βHow?β protection |
11. Best Practices π‘
- β Use abstraction to enforce method rules across subclasses
- β Keep abstract classes simple and meaningful
- β Use descriptive names for abstract methods
- β Avoid adding unnecessary abstract methods
Conclusion π
You now fully understand Abstraction in Python! Want the next topic? Try Encapsulation, Inheritance, Polymorphism, or Magic Methods. Just tell me! π