What is abstraction in Python OOP?
a) Hiding implementation details while showing only essential features
b) Creating multiple instances of a class
c) Defining a method with no body
d) Inheriting properties from another class
Answer:
a) Hiding implementation details while showing only essential features
Explanation:
Abstraction in Python OOP involves hiding the complex implementation details of a class while exposing only the essential features. This allows users of the class to interact with its public interface without needing to understand the underlying complexity.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
# Creating an object of Rectangle class
rect = Rectangle(5, 10)
print(rect.area()) # Output: 50
In this example, the Shape
class is an abstract base class with an abstract method area()
. The Rectangle
class inherits from Shape
and implements the area()
method. The user interacts with the Rectangle
class without needing to know the implementation details of how the area is calculated.
Abstraction simplifies code interaction by providing a clear and simple interface, making it easier to use and maintain the code.