Skip to content
TryHired.
Interview prep · Technical · Python 3.12.10

OOP interview questions: answers with real Python output

Object-oriented programming questions for developer interviews in any language, answered in plain words, with Python examples that were actually run.

Updated Nov 16, 2026 · Examples run with Python 3.12.10 · questions: TryHired
Quick answer

OOP interviews ask about classes and objects, the four pillars (encapsulation, abstraction, inheritance and polymorphism), abstract classes and interfaces, method resolution with super(), class and static methods, properties, equality and hashing, dataclasses, overloading versus overriding, composition versus inheritance, the Liskov principle, protocols and __slots__. Below are 15 questions; 14 examples were run with Python and show real output. The concepts carry over to Java, C# and C++.

Basic

Basic OOP interview questions

Advice

Basic1. What is the difference between a class and an object?

A class is a blueprint: it defines the data (attributes) and behavior (methods) its instances have. An object is one instance created from it, with its own state. A classic trap is a mutable class attribute: it belongs to the class, so every instance shares it, while attributes set on self belong to one instance.

Python
class Candidate:
    skills = []                     # class attribute: shared by every instance
    def __init__(self, name):
        self.name = name            # instance attribute: one per object
        self.applications = []

ava, ben = Candidate("Ava"), Candidate("Ben")
ava.skills.append("SQL")
ava.applications.append("Data Analyst")
print("Ben's skills:", ben.skills, "| Ben's applications:", ben.applications)
print("same list object:", ava.skills is ben.skills)
Output (Python 3.12.10)
Ben's skills: ['SQL'] | Ben's applications: []
same list object: True

Checked against: Python tutorial: classes

Basic2. What are the four pillars of OOP?

Encapsulation (bundle data with the methods that use it and hide internal details), abstraction (expose what an object does, not how), inheritance (a class reuses and extends another) and polymorphism (one interface, many implementations). Expect a follow-up asking for an example of each from your own code, so prepare one.

Basic3. How does encapsulation work in Python, given that it has no private keyword?

By convention: a name starting with one underscore is internal and should not be used from outside. A name starting with two underscores (and not ending with two) is name-mangled to _ClassName__name, which avoids accidental clashes in subclasses but does not make it secret. Expose controlled access through methods or properties instead.

Python
class Account:
    def __init__(self, balance):
        self._currency = "USD"     # internal by convention
        self.__balance = balance    # name-mangled
    def balance(self):
        return self.__balance

a = Account(100)
print(a.balance(), a._currency)
print(hasattr(a, "__balance"), [n for n in vars(a) if "balance" in n])
Output (Python 3.12.10)
100 USD
False ['_Account__balance']

Checked against: Python tutorial: classes

Basic4. What is polymorphism? Show an example.

Code written against a common interface works with any object that provides it. In Python this is often duck typing: the function below calls area() on whatever it receives, without checking the type, and each class supplies its own version (method overriding).

Python
import math
class Shape:
    def area(self): raise NotImplementedError
class Circle(Shape):
    def __init__(self, r): self.r = r
    def area(self): return math.pi * self.r ** 2
class Square(Shape):
    def __init__(self, s): self.s = s
    def area(self): return self.s ** 2
class Plot:                         # not a Shape, but it has area()
    def area(self): return 120.0

for thing in (Circle(1), Square(3), Plot()):
    print(type(thing).__name__, round(thing.area(), 2))
Output (Python 3.12.10)
Circle 3.14
Square 9
Plot 120.0

Checked against: Python docs: glossary

Intermediate

Intermediate OOP interview questions

Advice

Intermediate5. What is an abstract class, and how do you make one in Python?

An abstract class defines an interface that subclasses must implement and cannot be instantiated itself. In Python you inherit from abc.ABC and mark methods with @abstractmethod; creating an instance of a class that still has abstract methods raises TypeError.

Python
from abc import ABC, abstractmethod
class Notifier(ABC):
    @abstractmethod
    def send(self, message): ...
class EmailNotifier(Notifier):
    def send(self, message): return f"email: {message}"

print(EmailNotifier().send("Interview booked"))
try:
    Notifier()
except TypeError as e:
    print("TypeError:", e)
Output (Python 3.12.10)
email: Interview booked
TypeError: Can't instantiate abstract class Notifier without an implementation for abstract method 'send'

Checked against: Python docs: abc

Intermediate6. How does super() work with multiple inheritance?

Python looks up methods along the class's method resolution order (MRO), computed by C3 linearization: each class appears before its parents, and the order of the bases is kept. super() calls the next class in that order, not simply the parent, which is why cooperative classes in a diamond all run exactly once.

Python
class Base:
    def setup(self): print("Base.setup")
class Logging(Base):
    def setup(self): print("Logging.setup"); super().setup()
class Caching(Base):
    def setup(self): print("Caching.setup"); super().setup()
class Service(Logging, Caching):
    def setup(self): print("Service.setup"); super().setup()

print([c.__name__ for c in Service.__mro__])
Service().setup()
Output (Python 3.12.10)
['Service', 'Logging', 'Caching', 'Base', 'object']
Service.setup
Logging.setup
Caching.setup
Base.setup

Checked against: Python docs: built-in functions, Python docs: the Python 2.3 method resolution order

Intermediate7. What is the difference between instance methods, class methods and static methods?

An instance method receives the instance (self) and works with its state. A @classmethod receives the class (cls) and is typically used for alternative constructors, which then work for subclasses too. A @staticmethod receives neither; it is a plain function kept in the class's namespace because it belongs there logically.

Python
class Salary:
    def __init__(self, annual): self.annual = annual
    @classmethod
    def from_hourly(cls, rate, hours=2080): return cls(rate * hours)
    @staticmethod
    def is_valid(amount): return amount > 0
    def monthly(self): return round(self.annual / 12, 2)

s = Salary.from_hourly(30)
print(type(s).__name__, s.annual, s.monthly(), Salary.is_valid(-5))
Output (Python 3.12.10)
Salary 62400 5200.0 False

Checked against: Python docs: built-in functions

Intermediate8. What is a property, and why use one instead of a getter method?

@property turns a method into an attribute-style accessor, so you can add validation or computation later without changing the code that uses the attribute. A setter can reject bad values, which is encapsulation in practice.

Python
class Offer:
    def __init__(self, salary): self.salary = salary
    @property
    def salary(self): return self._salary
    @salary.setter
    def salary(self, value):
        if value <= 0: raise ValueError("salary must be positive")
        self._salary = value

o = Offer(90000)
o.salary = 95000
print(o.salary)
try:
    o.salary = -1
except ValueError as e:
    print("ValueError:", e)
Output (Python 3.12.10)
95000
ValueError: salary must be positive

Checked against: Python docs: built-in functions

Intermediate9. Why does a class that defines __eq__ stop being hashable?

If a class overrides __eq__ without defining __hash__, Python sets __hash__ to None, so its instances cannot go into sets or be dictionary keys. That protects the rule that equal objects must have equal hashes. Define __hash__ from the same fields used for equality (and keep those fields unchanged), or use a frozen dataclass.

Python
class Job:
    def __init__(self, title): self.title = title
    def __eq__(self, other): return isinstance(other, Job) and self.title == other.title

print(Job("Nurse") == Job("Nurse"), Job.__hash__)
try:
    {Job("Nurse")}
except TypeError as e:
    print("TypeError:", e)
Output (Python 3.12.10)
True None
TypeError: unhashable type: 'Job'

Checked against: Python reference: data model

Advanced

Advanced OOP interview questions

Advice

Advanced10. What do dataclasses generate for you?

@dataclass writes __init__, __repr__ and __eq__ from the annotated fields. frozen=True makes instances immutable (assignment raises an error) and, together with eq, makes them hashable. order=True adds comparison methods. Use field(default_factory=list) for mutable defaults instead of a shared list.

Python
from dataclasses import dataclass, field, FrozenInstanceError
@dataclass(frozen=True, order=True)
class Version:
    major: int
    minor: int
    tags: tuple = field(default=(), compare=False)

v1, v2 = Version(1, 4), Version(1, 10)
print(v1, v1 < v2, len({v1, Version(1, 4)}))
try:
    v1.major = 2
except FrozenInstanceError as e:
    print("FrozenInstanceError:", e)
Output (Python 3.12.10)
Version(major=1, minor=4, tags=()) True 1
FrozenInstanceError: cannot assign to field 'major'

Checked against: Python docs: dataclasses

Advanced11. Does Python support method overloading?

Not by signature, as Java and C# do: defining a method twice with the same name simply replaces the first definition. The usual alternatives are default and keyword arguments, *args, or functools.singledispatchmethod, which chooses an implementation by the type of the first argument after self.

Python
from functools import singledispatchmethod
class Formatter:
    def show(self, x): return "first definition"
    def show(self, x): return "second definition"   # replaces the first
    @singledispatchmethod
    def fmt(self, x): return f"value {x!r}"
    @fmt.register
    def _(self, x: int): return f"int {x:,}"
    @fmt.register
    def _(self, x: list): return f"list of {len(x)}"

f = Formatter()
print(f.show(1), "|", f.fmt(1234567), "|", f.fmt([1, 2]), "|", f.fmt("x"))
Output (Python 3.12.10)
second definition | int 1,234,567 | list of 2 | value 'x'

Checked against: Python docs: functools

Advanced12. When would you choose composition over inheritance?

Use inheritance for a genuine is-a relationship where the subclass can stand in anywhere the parent is expected; otherwise, prefer composition: build objects from smaller parts and delegate to them. Composition keeps classes small and lets you swap behavior at runtime, as the example does with the notification channel. This is a widely used design guideline rather than a language rule.

Python
class EmailChannel:
    def send(self, to, text): return f"email to {to}: {text}"
class SmsChannel:
    def send(self, to, text): return f"sms to {to}: {text}"
class Reminder:
    def __init__(self, channel): self.channel = channel      # has-a, not is-a
    def remind(self, to): return self.channel.send(to, "Interview at 10:00")

r = Reminder(EmailChannel())
print(r.remind("ava"))
r.channel = SmsChannel()
print(r.remind("ava"))
Output (Python 3.12.10)
email to ava: Interview at 10:00
sms to ava: Interview at 10:00

Advanced13. What is the Liskov substitution principle? Give an example of breaking it.

One of the SOLID design principles: code that works with a base class should keep working with any subclass. The classic violation is a Square that inherits from Rectangle: setting the width of a square also changes its height, so code that relies on rectangle behavior gets a wrong result. Like the rest of SOLID, it is a design guideline, not something the language enforces.

Python
class Rectangle:
    def __init__(self, w, h): self.w, self.h = w, h
    def set_width(self, w): self.w = w
    def area(self): return self.w * self.h
class Square(Rectangle):
    def __init__(self, s): super().__init__(s, s)
    def set_width(self, w): self.w = self.h = w

def stretch(rect):
    rect.set_width(10)
    return rect.area()          # caller expects 10 * original height

print("Rectangle(2, 5):", stretch(Rectangle(2, 5)), "| Square(5):", stretch(Square(5)))
Output (Python 3.12.10)
Rectangle(2, 5): 50 | Square(5): 100

Advanced14. What is a Protocol in Python typing?

typing.Protocol describes an interface structurally: any class with the right methods matches, without inheriting from it. Type checkers use it for static duck typing. With @runtime_checkable, isinstance() also works, but it only checks that the methods exist, not their signatures.

Python
from typing import Protocol, runtime_checkable
@runtime_checkable
class Exporter(Protocol):
    def export(self) -> str: ...
class CsvReport:
    def export(self) -> str: return "a,b\n1,2"
class Chart:
    def render(self) -> str: return "<svg/>"

print(isinstance(CsvReport(), Exporter), isinstance(Chart(), Exporter))
Output (Python 3.12.10)
True False

Checked against: Python docs: typing

Advanced15. What does __slots__ do?

Declaring __slots__ reserves space for a fixed set of attributes and, when every class in the hierarchy defines slots, stops Python from creating a per-instance __dict__. That saves memory for large numbers of small objects and turns misspelled attribute assignments into errors.

Python
class Point:
    __slots__ = ("x", "y")
    def __init__(self, x, y): self.x, self.y = x, y

p = Point(1, 2)
print(hasattr(p, "__dict__"))
try:
    p.z = 3
except AttributeError as e:
    print("AttributeError:", e)
Output (Python 3.12.10)
False
AttributeError: 'Point' object has no attribute 'z'

Checked against: Python reference: data model

Practice

How to practice with this page

Advice
  • Explain each pillar with an example from code you wrote.
  • For each answer, say how it differs in the language the role uses (Java, C# or Python).
  • Refactor a small inheritance hierarchy into composition and explain the trade-off.
  • Prepare one design pattern you have used and why.
Next

Related interview prep and tools

Disclosure: TryHired makes HIRED, a paid job-search program, so we have a conflict of interest when we mention it. This question bank is free, with no TryHired signup.

FAQ

Questions people ask

Which language should I use for OOP interview answers?
Use the language of the role. The concepts are the same in Java, C#, C++ and Python, but the details differ: Python has no access modifiers and no signature overloading, while Java and C# have both, and C++ adds multiple inheritance with its own rules. The examples here use Python because they could be run on this page.
What OOP topics come up often in interviews?
The four pillars with your own examples, abstract classes versus interfaces, overloading versus overriding, composition versus inheritance, SOLID, and design patterns such as factory, strategy and observer.
Are design patterns part of OOP interviews?
Often, for mid-level and senior roles. Know a few well (factory, strategy, observer, adapter, decorator) and be ready to say when you would not use one.
Method

How this page is built

TryHired wrote these questions and answers. Every code block on this page was run with Python 3.12.10 when the page was built (2026-11-16), using only the standard library. The output shown is the real output, including error messages where an example demonstrates an exception, and the build stops if any example fails. The question list is general practice: it does not predict what a particular employer will ask.

What this page can't tell you
  • Interviewers ask different questions for different roles and levels.
  • Answers are short explanations, not complete references.
  • Examples use Python 3.12. Python has no access modifiers and no signature overloading, so those answers explain how the idea maps to Python and how it differs in Java and C#. SOLID and composition advice are design guidelines, not language rules.
Sources
  1. Python docs: abc (read 2026-11-15)
  2. Python tutorial: classes (read 2026-11-15)
  3. Python docs: dataclasses (read 2026-11-15)
  4. Python reference: data model (read 2026-11-15)
  5. Python docs: built-in functions (read 2026-11-15)
  6. Python docs: functools (read 2026-11-15)
  7. Python docs: glossary (read 2026-11-15)
  8. Python docs: the Python 2.3 method resolution order (read 2026-11-15)
  9. Python docs: typing (read 2026-11-15)