Junior — Middle
How are key object-oriented programming concepts implemented in Python?
sobes.tech AI
Answer from AI
In Python, the key concepts of object-oriented programming (OOP) are implemented as follows:
-
Classes and objects: a class is a template for creating objects.
-
Encapsulation: hiding internal implementation through conventions (e.g., _protected and __private attributes).
-
Inheritance: creating a new class based on an existing one.
-
Polymorphism: the ability to use objects of different classes through a common interface.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass # base method
class Dog(Animal):
def speak(self):
return f'{self.name} says: Woof!'
class Cat(Animal):
def speak(self):
return f'{self.name} says: Meow!'
animals = [Dog('Sharik'), Cat('Murka')]
for animal in animals:
print(animal.speak())
This demonstrates inheritance (Dog and Cat from Animal), polymorphism (different implementations of the speak method), and encapsulation through class attributes.