Sobes.tech
Junior — Middle

How well does Python support object-oriented programming principles?

sobes.tech AI

Answer from AI

Python strongly supports the core principles of object-oriented programming (OOP):

  • Encapsulation: classes and objects allow hiding internal data and methods using naming conventions (e.g., _private or __mangled).
  • Inheritance: Python supports multiple inheritance, enabling the creation of class hierarchies.
  • Polymorphism: thanks to dynamic typing and duck typing, objects of different classes can be used interchangeably if they have the required methods.
  • Abstraction: abstract base classes can be created using the abc module.

Example of a simple class with inheritance and encapsulation:

from abc import ABC, abstractmethod

class Animal(ABC):
    def __init__(self, name):
        self._name = name  # protected attribute

    @abstractmethod
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return f"{self._name} says: Woof!"

dog = Dog("Bobby")
print(dog.speak())  # Bobby says: Woof!

Thus, Python provides flexible and powerful tools for OOP, although with some features, such as the absence of strict privacy.