Sobes.tech
Junior — Middle

Can you explain the principles of object-oriented programming in Python?

sobes.tech AI

Answer from AI

Object-oriented programming (OOP) in Python is based on four main principles:

  1. Encapsulation — combining data and methods that operate on that data into a single object (class). This allows hiding internal implementation details and protecting data from direct access.

  2. Inheritance — a mechanism that allows creating a new class based on an existing one, inheriting its properties and methods, which promotes code reuse.

  3. Polymorphism — the ability of objects of different classes to respond to the same messages (methods) in different ways. In Python, this is achieved through method overriding.

  4. Abstraction — highlighting the essential characteristics of an object while hiding non-essential details.

Example of a class in Python:

class Animal:
    def __init__(self, name):
        self.name = name  # data encapsulation

    def speak(self):
        pass  # abstract method

class Dog(Animal):  # inheritance
    def speak(self):
        return f"{self.name} says: Woof!"  # polymorphism

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