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()
Output:
TypeError: Can't instantiate abstract class Demo without an implementation for abstract method 'display'
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()
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()
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.
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)
Output:
100000
100
AttributeError: 'Infosys' object has no attribute '__project_bid'
Top comments (0)