Python OOP Interview Questions with Worked Answers

Python OOP interview questions test how classes create objects, how methods receive their arguments, and how callers use interchangeable implementations. Explain inheritance and composition with a small design, then trace what actually happens. This guide works through a report formatter, clarifies __new__ versus __init__, and covers properties, abstract interfaces, method resolution and dataclasses.

Aug 27, 2024 - 17:53
Updated: 
103.9k

Python for AI & Automation in AI & Data · Interview preparation

Python OOP Interview Questions with Worked Answers

Quick answer: Python OOP interview questions test how classes create objects, how methods receive their arguments, and how callers use interchangeable implementations. Explain inheritance and composition with a small design, then trace what actually happens. This guide works through a report formatter, clarifies __new__ versus __init__, and covers properties, abstract interfaces, method resolution and dataclasses. The runnable example shows delegation and stored state; the answer cues explain the limits of privacy and immutability claims.

Key takeaways

  • Explain the caller contract before choosing inheritance.
  • Use composition when an output component changes independently.
  • Distinguish instance, class and static method binding.
  • Treat name mangling as collision avoidance.
  • Check dataclass and resource-lifetime assumptions.

Table of Contents

What is the difference between a class and an object?

A class defines behaviour and provides a way to create instances. An object is an individual instance with its own identity and state. In a reporting exercise, Report is the class; the weekly stock report and monthly sales report are separate objects. Both can use render(), while carrying different titles.

The class tutorial explains how methods receive an instance. The conventional parameter name self is not a reserved keyword. When you call report.render(), Python supplies report to that method. Start an interview answer with this relationship before listing inheritance, abstraction, encapsulation and polymorphism. Then explain one of those ideas with behaviour the interviewer can inspect.

How do __new__ and __init__ differ?

__new__ creates an instance; __init__ initializes an instance that has been created. The data model specifies their relationship. Calling __init__ a constructor is common shorthand, but saying it creates the object hides the distinction that a follow-up question usually tests.

For Report, initialization stores a title and a formatter. Put required checks here when invalid state must never be accepted. If a title must be non-empty, specify whether whitespace-only text is invalid before implementing the check. Ordinary application classes rarely need a custom __new__; immutable-type construction is a more relevant reason to investigate it than adding a singleton to every example.

When should you choose composition instead of inheritance?

Question: a report needs two output styles. Should UpperReport inherit from Report? Composition lets a Report hold a formatter and delegate formatting to it. Swapping that collaborator changes output without creating another report subclass. Both formatter objects provide the required format method, an example of duck typing.

Run this complete offline exercise. The first two lines change because the formatter changes; the final line shows the stored title is unchanged. No file is written. The example has been checked in CPython 3.14.4.

class Plain:
    def format(self, title):
        return title

class Upper:
    def format(self, title):
        return title.upper()

class Report:
    def __init__(self, title, formatter):
        self._title = title
        self.formatter = formatter

    @property
    def title(self):
        return self._title

    def render(self):
        return self.formatter.format(self.title)

report = Report("weekly stock", Plain())
print(report.render())
report.formatter = Upper()
print(report.render())
print(report.title)

Expected output:

weekly stock
WEEKLY STOCK
weekly stock
Design choiceUseful whenQuestion to ask
CompositionA component varies independentlyCan another formatter satisfy the same contract?
InheritanceA subtype can honour the base behaviourWill every caller still work with this subtype?
Plain functionThere is no lasting instance stateWould a class make the call clearer?

Inheritance can still be appropriate. The interview answer should justify the relationship, including what callers are allowed to rely on.

What do instance, class and static methods receive?

An instance method receives the instance. A classmethod receives the class, which makes it useful for alternative factories that should construct the actual subclass. A staticmethod receives no implicit instance or class. These are binding rules, not rules about whether a function can change state; a static method can still mutate an argument or a global.

The built-in function reference documents classmethod, staticmethod and super. In multiple inheritance, super follows the method resolution order after the current class. It does not always mean the immediately named parent. Ask candidates to explain a cooperative diamond by tracing the MRO and checking compatible method signatures, rather than manually invoking both parents and risking duplicate work.

How do abstraction and polymorphism work in Python?

Polymorphism lets callers use the same operation with different implementations. Report.render() needs format(title); it does not need a particular formatter class. An abstract base class can make required methods explicit and prevent instantiation while abstract methods remain unimplemented. The abc reference explains that mechanism.

A typing Protocol describes a structural interface for type-checking tools. The typing reference also states that annotations are not generally enforced by the runtime. An annotated formatter parameter therefore does not automatically reject an object lacking format(). Choose an ABC when runtime abstract-class machinery serves the design; use structural typing when independent implementations should share a documented shape.

Are properties and double underscores security boundaries?

A property presents method-backed attribute access. Report.title has a getter and no setter, so assigning to that property raises an error. However, the _title convention asks callers to avoid an implementation detail; it does not stop them accessing it. A double-leading-underscore name triggers name mangling, mainly to reduce accidental collisions in subclasses.

Interview claimMore precise answer
A private name cannot be accessedName mangling changes lookup names; it is not access control
A getter-only property makes an object immutableOther attributes and referenced mutable objects may still change
self is a keywordIt is the established name for the instance parameter
super calls the parentIt delegates according to the MRO

For a follow-up, ask whether returning an internal list from a property gives callers a route to mutate the object. A copy or immutable view may fit the public contract better.

When would you use a dataclass or a context manager?

A dataclass can reduce repetitive record code by generating methods such as initialization, representation and equality. The dataclasses reference makes generation conditional on the options and existing definitions. Hashing is not generated unconditionally. Frozen instances restrict normal field assignment, but a mutable object stored inside a field can still change.

Resource lifetime is a separate question. Use a context manager for a resource that needs prompt cleanup; do not depend on __del__ running at a particular moment. In an interview, compare a record holding a report title with a managed output stream: the first needs clear value semantics, while the second needs a defined closing boundary. Avoid putting secrets into __repr__, because debugging output can expose them.

Related reading: Advanced Python protocols; Common Python behaviour questions; Python data structures.

References

Frequently Asked Questions

Classes and objects support encapsulation, abstraction, inheritance and polymorphism, which are best explained through a concrete caller and implementation.

Self is a naming convention for an instance parameter, and Python supplies the instance when calling a bound method.

The __new__ method creates an instance, while __init__ normally initializes that instance after creation has taken place.

Double-leading-underscore names undergo name mangling, which reduces accidental subclass collisions but does not provide a security boundary.

A static method receives no implicit receiver, but its code can still change supplied mutable objects or accessible global state.

Frozen dataclasses restrict ordinary assignment to fields, while mutable objects referenced by those fields can still be modified.

Composition is useful when collaborators vary independently, such as replacing a report formatter while preserving the report interface.

Super delegates to the next implementation in the method resolution order, which may include another branch of multiple inheritance.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Wow Wow 0
Sad Sad 0
Angry Angry 0
Anjali

I am passionate about technology, invention and big challenging tasks on my to- do list. In terms of the work I am doing also at Bunnyshell, I am most passionate about the technologies that we are using., I'm devoted to delivering content that not only informs but also inspires. Whether you need in- depth analysis pieces, educational attendants, or study- provoking opinion pieces, I draft content that resonates with tech suckers and professionals likewise.