DEV Community

Guru prasanna
Guru prasanna

Posted on

2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

If you found this post helpful, please leave a ❤️ or a friendly comment below!

Okay