Middle
What are the principles of OOP in Python?
sobes.tech AI
Answer from AI
The main principles of object-oriented programming (OOP) in Python include:
- Encapsulation — combining data and methods that operate on that data within a single class, as well as hiding internal implementation details from the outside world.
- Inheritance — the ability to create new classes based on existing ones, inheriting their properties and methods.
- Polymorphism — the ability of objects of different classes to respond to the same messages (method calls) in different ways.
- Abstraction — highlighting common characteristics and behaviors of objects, hiding implementation details.
Example:
class Animal:
def speak(self):
pass
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()) # Demonstrates polymorphism