Junior
What principles of object-oriented programming do you know?
sobes.tech AI
Answer from AI
Encapsulation, inheritance, polymorphism.
-
Encapsulation: Combining data (attributes) and methods that operate on this data into a single entity — an object. Hiding the internal implementation of the object from the external environment.
class Car: def __init__(self, make, model): self._make = make # Protected attribute self._model = model # Protected attribute def get_description(self): # Method provides access to data return f"Brand: {self._make}, Model: {self._model}" # External code interacts through methods my_car = Car("Toyota", "Camry") print(my_car.get_description()) -
Inheritance: The ability to create new classes (subclasses) that inherit attributes and methods from existing classes (superclasses).
class Animal: def speak(self): pass # Base method class Dog(Animal): def speak(self): return "Woof!" # Override method class Cat(Animal): def speak(self): return "Meow!" # Override method # Using inherited and overridden methods my_dog = Dog() my_cat = Cat() print(my_dog.speak()) print(my_cat.speak()) -
Polymorphism: The ability of objects of different classes to respond to the same message (method call) in different ways.
class Shape: def area(self): pass # Base method for calculating area class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height # Implementation for rectangle class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): import math return math.pi * self.radius**2 # Implementation for circle # Objects of different classes calling the same "area" method rectangle = Rectangle(5, 10) circle = Circle(7) shapes = [rectangle, circle] # Behavior of "area" method depends on object type for shape in shapes: print(f"Area: {shape.area()}")