Sobes.tech
Middle

Name the main principles of OOP and how they are implemented in Python?

sobes.tech AI

Answer from AI

Object-Oriented Programming (OOP) principles:

  • Encapsulation — combining data and methods that work with that data into a single object, hiding internal implementation.
  • Inheritance — creating new classes based on existing ones, allowing code reuse.
  • Polymorphism — the ability of objects of different classes to respond to the same messages (methods) in different ways.
  • Abstraction — highlighting essential characteristics of an object, hiding implementation details.

In Python, these principles are implemented through classes and objects. For example:

class Animal:
    def speak(self):
        pass  # abstract method

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

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

animals = [Dog(), Cat()]
for animal in animals:
    print(animal.speak())  # polymorphism

Encapsulation is achieved through conventions about privacy (e.g., _private or __private), inheritance through subclassing, polymorphism through method overriding, and abstraction through base classes and interfaces.