Day 9: OOPS in Python - Abstraction and Encapsulation

RishithaRishitha
2 min read

Abstraction

It is the process of hiding the implementation details of a class and only showing the essential features to the user.

For example, when you drive a car, you don’t need to understand how the engine works internally. You only need to know how to accelerate, brake, and steer. Similarly, abstraction in Python hides unnecessary details from the user and only exposes essential functionalities.

#Car class definition
class Car:
    #__init__ constructor
    def __init__(self):
        self.acc = False
        self.brk = False

    #car_start obj method
    def car_start(self):
        self.brk = True
        self.acc = True
        print("Car started..")

#creating obj of car class       
car1 = Car()

#obj method call
car1.car_start()

#output
#Car started..

Encapsulation

Encapsulation restricts access to data and methods by defining different access levels for class attributes and methods. This ensures that sensitive data is protected and can only be modified or accessed in a controlled manner. Uses getter and setter methods to control access.

How Encapsulation Restricts Access?

Encapsulation achieves this restriction using:

1. Public Members – Accessible from anywhere.

2. Protected Members (_var) – Intended for internal use but still accessible.

3. Private Members (__var) – Strictly controlled access.

Private(like) attributes & methods

Conceptual Implementations in Python

  • Private attributes and methods are meant to be used only within the class and are not accessible from outside the class.
#Unsecured code
class Account:
    def __init__(self, accNo, accPass):
        self.accNo = accNo
        self.accPass = accPass

acc1 = Account("1234","hello")
print(acc1.accNo)
print(acc1.accPass)

#Output:
1234
hello

If there’s any sensitive information which we don’t want them to be accessible outside the class, we can make them Private. (By just adding 2 underscores before an attribute)

class Account:
    def __init__(self, accNo, accPass):
        self.accNo = accNo
        self.__accPass = accPass

acc1 = Account("1234","hello")
print(acc1.accNo) 
print(acc1.__accPass) 

#Output:
#AttributeError: 'Account' object has no attribute '__accPass'

class Account:
    def __init__(self, accNo, accPass):
        self.accNo = accNo
        self.__accPass = accPass

    def reset_pass(self):
        print(self.__accPass)

acc1 = Account("1234","hello")
print(acc1.accNo)
print(acc1.reset_pass())
#output:
1234
hello
None
class Person:
    __name = "anonymous"

    def __hello(self):
        print("hello person!")

    def welcome(self):
        self.__hello()
p1 = Person()
p1.welcome()
#output:
hello person!
0
Subscribe to my newsletter

Read articles from Rishitha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rishitha
Rishitha