Interview Q&A / Object-Oriented Programming

IntermediateQuick answer1 min readUpdated 3 Oct 2026

How would you build a simple factory in Python without a long if-elif chain?

SHORT ANSWER

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.

Explain it simply

A railway enquiry counter has a board listing "train name -> platform". The staff do not reason it out each time; they look it up. A dictionary of classes is that board for your factory.

Example

python
class PdfExporter:
    def export(self, data): return f"PDF({data})"

class CsvExporter:
    def export(self, data): return f"CSV({data})"

EXPORTERS = {
    "pdf": PdfExporter,
    "csv": CsvExporter,
}

def make_exporter(kind):
    try:
        return EXPORTERS[kind]()
    except KeyError:
        raise ValueError(f"unknown exporter: {kind}")

print(make_exporter("pdf").export("report"))   # PDF(report)
print(make_exporter("csv").export("report"))   # CSV(report)

EXPORTERS["json"] = type("JsonExporter", (), {"export": lambda self, d: f"JSON({d})"})
print(make_exporter("json").export("report"))  # JSON(report)

Classes are objects in Python, so they can be stored in a dictionary and called later. Plugins can register themselves without editing the factory function.

What to say in the interview

"I use a registry dictionary from key to class, and instantiate from it. It removes the branching chain, gives a clear error for unknown keys, and lets new types register themselves, which fits the Open/Closed Principle."

Common mistakes

  • Silently returning None for unknown keys. Raise a clear error.

#factory#python#design-patterns

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.