What is abstraction in Python oops with example.
Abstraction is a OOP concept, that allows you to hide complex implementation details and only show the essential features of an object.
This is achieved using abstract classes and abstract methods. Abstract classes act as blueprints for other classes, enforcing a structure without implementing the details.
Example of abstraction:
Think of a TV and its remote control as an example of abstraction. When you press a button on the remote, the channel changes, volume adjusts, or the TV turns on or off. You, as the user, don’t need to understand how the remote sends signals to the TV, how the TV decodes these signals, or how the internal circuits work to perform these actions. All you care about is pressing the button and seeing the result.
Syntax of abstraction:
from abc import ABC, abstractmethod
class AbstractClass(ABC):
@abstractmethod
def abstract_method(self):
pass
Key Points of Abstraction
- Abstract Class: A class that cannot be instantiated and usually contains one or more abstract methods.
To create a class is the abstract class we just inherit that class by the ABC class.
Example:
from abc import ABC, abstractmethod
class Class_Name(ABC): # Abstract class
# block of code
- Abstract Method: A method that is declared but contains no implementation. Subclasses are required to implement it.
To create a method, abstract method we only need to write @abstractmethod on that method.
Example:
from abc import ABC, abstractmethod
class ClassName(ABC): # Abstract class
@abstractmethod
def method_name(self): # Abstract method
pass
Example of abstraction:
from abc import ABC, abstractmethod
class Animal(ABC): # Abstract class
@abstractmethod
def sound(self): # Abstract method
pass
class Dog(Animal): # Child class
def sound(self):
print("Woof!")
class Cat(Animal): # Another child class
def sound(self):
print("Meow!")
# Usage
dog = Dog()
cat = Cat()
dog.sound()
cat.sound()
Output:
Woof!
Meow!
20+ interview questions on Abstraction in Python with answers and examples to clarify each concept.
Question 1. What is abstraction in Python OOP?
Answer: Abstraction in Python is a way of hiding implementation details and exposing only the necessary parts to the user. It simplifies complex systems by focusing on essential features rather than internal workings.
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Bark"
dog = Dog()
print(dog.sound())
Output:
Bark
Question 2. How do you achieve abstraction in Python?
Answer: Abstraction is achieved using abstract classes and abstract methods, which can be created using the ABC class from the abc module and the @abstractmethod decorator.
Example:
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def fuel_type(self):
pass
Question 3. What is an abstract class?
Answer: An abstract class is a class that cannot be instantiated and is designed to be subclassed. It may contain abstract methods that must be implemented by any subclass.
Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
Question 4. Can you create an instance of an abstract class?
Answer: No, an abstract class cannot be instantiated directly.
Example:
shape = Shape() # Raises TypeError: Can't instantiate abstract class
Question 5. What is an abstract method?
Answer: An abstract method is a method declared in an abstract class without any implementation. Subclasses must provide their implementation.
Example:
class Shape(ABC):
@abstractmethod
def area(self):
pass
Question 6. What module is used to create abstract classes in Python?
Answer: The abc module is used, and it provides the ABC class and @abstractmethod decorator.
Question 7. Can an abstract class have regular methods?
Answer: Yes, an abstract class can have both abstract and regular methods.
Example:
class Vehicle(ABC):
@abstractmethod
def fuel_type(self):
pass
def start(self):
return "Vehicle started"
Question 8. Why do we use abstract classes in Python?
Answer: Abstract classes provide a blueprint for other classes, enforce implementation of certain methods, and promote code reusability and modularity.
Question 9. Explain how abstraction differs from encapsulation.
Answer: Abstraction hides complexity by exposing only necessary parts, while encapsulation hides internal data by restricting access through methods.
Question 10. Can a subclass skip implementing an abstract method from the parent class?
Answer: No, if a subclass does not implement all abstract methods, it will also be considered abstract and cannot be instantiated.
Question 11. Give an example of a scenario where abstraction would be useful.
Answer: Abstraction is useful in scenarios like payment processing, where different types of payments (e.g., credit card, PayPal) require different implementations but follow the same interface.
Question 12. Can an abstract class have a constructor?
Answer: Yes, abstract classes can have constructors to initialize data that might be used by subclasses.
Example:
class Animal(ABC):
def __init__(self, name):
self.name = name
Question 13. Is it possible to define a concrete method in an abstract class?
Answer: Yes, an abstract class can have concrete methods, which can be inherited by subclasses.
Question 14. What is the @abstractmethod decorator used for?
Answer: The @abstractmethod decorator is used to define an abstract method within an abstract class.
Question 15. How does Python enforce the implementation of abstract methods?
Answer: Python enforces abstract methods by raising a TypeError if an abstract class is instantiated without implementing all abstract methods.
Question 16. Can you have multiple abstract classes in Python?
Answer: Yes, Python allows multiple abstract classes and even supports multiple inheritance with abstract classes.
Question 17. Give an example of using inheritance with abstraction.
Example:
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
Question 18. What happens if a subclass does not implement all abstract methods?
Answer: The subclass will be considered abstract and cannot be instantiated.
Question 19. Can abstract methods have default implementations?
Answer: No, abstract methods cannot have implementations. However, regular methods in abstract classes can have implementations.
Question 20. How is abstraction different from interface in other languages?
Answer: In Python, abstract classes serve a similar role to interfaces in other languages by defining methods that subclasses must implement. However, Python doesn’t have a separate interface type.
Question 21. Give an example of abstraction to define a Shape class with a calculate_area method.
Example:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def calculate_area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return 3.14159 * self.radius ** 2
circle = Circle(5)
print(circle.calculate_area())
Output:
78.53975
Question 22. What is the purpose of the ABC class in Python?
Answer: ABC is a built-in class in the abc module, which allows a class to become abstract by defining abstract methods using the @abstractmethod decorator.
Tags:
Leave a comment
You must be logged in to post a comment.