Junior — Middle
In which situations is it preferable to use a class in Python?
sobes.tech AI
Answer from AI
Python classes are preferred when you need to:
- Combine data and behavior (methods) in one structure.
- Create objects with a mutable state.
- Implement encapsulation, inheritance, and polymorphism.
- Organize code for reuse and extensibility.
For example, if you need to describe an entity "Car" with characteristics and methods:
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def drive(self):
print(f"{self.make} {self.model} is driving")
car = Car("Toyota", "Camry")
car.drive() # Toyota Camry is driving
If the task is simple and does not require state or methods, you can use functions or data structures.