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:
-
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.
-
Inheritance — a mechanism that allows creating a new class based on an existing one, inheriting its properties and methods, which promotes code reuse.
-
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.
-
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!