Sobes.tech
Junior — Middle

Can you explain the concept of abstraction in Python and its role in programming?

sobes.tech AI

Answer from AI

Abstraction in Python is a principle of object-oriented programming that allows hiding internal implementation details and showing only the necessary interface for interacting with an object. It helps simplify working with complex systems by focusing on what the object does rather than how it does it.

In Python, abstraction is achieved through:

  • Abstract classes and methods (module abc), where you can define methods that must be implemented in subclasses.
  • Encapsulation — hiding internal data and methods (for example, using naming conventions with one or two underscores).

Example with an abstract class:

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        return "Woof"

class Cat(Animal):
    def make_sound(self):
        return "Meow"

# Now you can work with Animal objects without knowing their specific type
animals = [Dog(), Cat()]
for animal in animals:
    print(animal.make_sound())

The role of abstraction is to improve readability, support, and extensibility of the code, as well as to reduce coupling between system components.