Code Crafter IT Innovation
Loading...
  • Bansal Computer Center
  • punjabedu.bansalcenter.com

Python Abstraction

What is Abstraction?

Abstraction means showing only what is necessary and hiding how it is done.

“Kya kaam ho raha hai dikhana, kaise ho raha hai chupana.”

Real-Life Example: Car Accelerator

When you press the accelerator, the car moves. You don’t need to know the complex engine logic or fuel injection process. You just use the functionality. That is abstraction.

Why is it needed?

Encapsulation vs Abstraction

It is very important to understand the difference between these two core OOPs concepts.

EncapsulationAbstraction
Data hidingLogic hiding
HOW data is protectedWHAT methods are available
Uses access modifiers (private/public)Uses abstract classes and methods
Example: private variables (__marks)Example: abstract methods

How Abstraction is Implemented

Python provides the abc module (Abstract Base Classes) to implement abstraction.

Key Components:

from abc import ABC, abstractmethod

class Animal(ABC): # Abstract Class
    @abstractmethod
    def sound(self): # Abstract Method
        pass

Step-by-Step Code Examples

1. Implementing the Child Class

If a child class inherits from an abstract class, it must define all abstract methods, or Python will throw an error.

class Dog(Animal):
    def sound(self):
        print("Dog barks")

d = Dog()
d.sound() # Output: Dog barks

2. Shape Example (Exam Friendly)

Commonly asked in interviews and exams to demonstrate functionality hiding.

from abc import ABC, abstractmethod

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

class Square(Shape):
    def area(self):
        print("Area = side × side")

s = Square()
s.area() # Output: Area = side × side

Quick Revision

Summary of core Abstraction concepts for quick reference.

ConceptMeaning
AbstractionProcess of hiding implementation details.
ABCThe module used to create abstract classes.
@abstractmethodDecorator used to define a method without logic.
Object CreationNot allowed for abstract classes (e.g., a = Animal() -> ERROR).

Exam One-Liner:

Definition: Abstraction is the process of hiding implementation details and showing only essential features to the user.

What students Say?

Here are the stdudents...

#

Contact Us

Empower your tech dreams with us. Get in touch!

  • #
  • #
  • #
  • #
  • #