Interview Q&A / Object-Oriented Programming

INTERVIEW Q&A · 69 QUESTIONS

Object-Oriented Programming interview questions

The four pillars, interfaces, abstract classes and design basics.

  1. How does dependency injection make unit testing easier?

    Because the class receives its collaborators, a test can pass in a fake instead of a real database, network or clock. The test runs fast and gives the same result every time.

    BeginnerQuick answer1 min read
  2. Show Dependency Inversion with a NotificationService that currently creates EmailSender inside itself.

    Define a Sender interface, have NotificationService depend on it, and pass the implementation in from outside. The service no longer knows whether it is sending email, SMS or WhatsApp.

    BeginnerQuick answer1 min read
  3. What is duck typing in Python, and how does it relate to polymorphism?

    Duck typing means an object is accepted if it has the methods you call, regardless of its class. It gives polymorphism without a shared parent or interface.

    BeginnerQuick answer1 min read
  4. What is self in Python class methods, and why must it be written?

    self is the first parameter of an instance method and receives the object the method was called on. Python passes it automatically; the name is only a convention.

    BeginnerQuick answer1 min read
  5. Does Python have private attributes? What do _x and __x mean?

    Python has no true private. A single underscore _x is a hint that it is internal. A double underscore __x triggers name mangling, which renames it to _ClassName__x to avoid clashes in subclasses.

    IntermediateQuick answer1 min read
  6. How would you build a simple factory in Python without a long if-elif chain?

    Keep a dictionary that maps names to classes and look the class up. Adding a new type is a one-line registration rather than another elif branch.

    IntermediateQuick answer1 min read
  7. What is the difference between a shallow copy and a deep copy of an object?

    A shallow copy duplicates the object but shares the objects it refers to. A deep copy duplicates the whole graph, so the copy shares nothing with the original.

    IntermediateQuick answer1 min read
  8. What is the method resolution order (MRO) in Python?

    MRO is the order in which Python searches a class and its parents when you call a method or read an attribute. Python builds it with the C3 rule, and you can see it in ClassName.__mro__.

    AdvancedQuick answer1 min read