DEV Community

Guru prasanna
Guru prasanna

Posted on

2 2 1 1 1

Python Day- 35 Abstraction , Encapsulation

Abstraction:

--> Abstraction is used to hide the internal functionality of the function from the users.
--> The users only interact with the basic implementation of the function, but inner working is hidden.
--> User is familiar with that "what function does" but they don't know "how it does."
--> Abstraction is implemented using abstract classes and abstract methods, which are provided by the abc (Abstract Base Class) module.

An abstract class is a class that cannot be instantiated (i.e., you cannot create an object of it). Abstract Methods Should Not Have a Body-pass should be given.

Example:1

from abc import *
class Demo(ABC):
    @abstractmethod
    def display(self):
        print("ABCD")

d = Demo()
d.display()
Enter fullscreen mode Exit fullscreen mode

Output:

TypeError: Can't instantiate abstract class Demo without an implementation for abstract method 'display'
Enter fullscreen mode Exit fullscreen mode

Example:2

from abc import *
class Parent(ABC):
    @abstractmethod
    def study(self):
        pass

class Child(Parent):
    def study(self):
        print("Commerce")

child = Child()
child.study()
Enter fullscreen mode Exit fullscreen mode

Output:
Commerce

Example:3

from abc import *
class Parent(ABC):
    @abstractmethod
    def study(self):
        pass

class Child(Parent):
    def study(self):
        print("Commerce")

    @abstractmethod
    def test(self):
        pass

class GrandChild(Child):
    def test(self):
        pass 
child = GrandChild()
child.study()
Enter fullscreen mode Exit fullscreen mode

Output:
Commerce

Encapsulation:

Encapsulation refers to the bundling of data (variables) and methods (functions) into a single unit (class) while restricting direct access to some of the object's details.

Features of Encapsulation:

--> Protects data from accidental modification
--> Hides the internal implementation and exposes only necessary details.

Image description

Example:

class Infosys:
    employees_count = 100000
    _profit = 100
    __project_bid = 50

    def display(self):
        print(self.employees_count, self._profit, self.__project_bid)

inf = Infosys()
#inf.display()
print(inf.employees_count)
print(inf._profit)
print(inf.__project_bid)
Enter fullscreen mode Exit fullscreen mode

Output:

100000
100
AttributeError: 'Infosys' object has no attribute '__project_bid'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more