Autocoder

Python OOPs Interview Questions

Last updated 2026-11-19

Object-oriented questions in Python interviews go beyond defining encapsulation and polymorphism. Interviewers want to see that you know how Python actually implements classes: attribute lookup, the method resolution order, the difference between class and instance attributes, and how special methods plug your objects into the language.

The questions below combine definitions with short programs you will be asked to trace. Pay attention to the class attribute traps and to super() in multiple inheritance, which are the two areas where candidates most often lose marks.

LevelFresher to 3 years
FocusClasses, inheritance, dunder methods
VersionPython 3.10 and later

What gets tested

Interviewers usually check four things: whether you can build a clean small class hierarchy, whether you understand self and cls, whether you know the common dunder methods, and whether you can predict behaviour when attributes live on the class rather than the instance.

Related reading

The language basics are on the main Python page. For a design-flavoured round, pair this with how to crack a Python interview.

Python OOPs Interview Questions: questions with worked answers

  1. 1

    What is the difference between a class attribute and an instance attribute?

    easy

    A class attribute is defined in the class body and shared by all instances. An instance attribute is set on self, usually in __init__, and belongs to one object. Reading looks at the instance first, then the class. Assigning through an instance always creates or updates an instance attribute and never changes the class attribute, but mutating a shared mutable class attribute, such as a list, affects every instance.

    python
    class A:
        items = []
        n = 0
    a, b = A(), A()
    a.items.append(1)
    a.n = 5
    print(b.items, b.n, A.n)   # [1] 0 0
  2. 2

    What are self and cls?

    easy

    self is the conventional name of the first parameter of an instance method and receives the instance. cls is the first parameter of a classmethod and receives the class itself, which makes it useful for alternative constructors that also work in subclasses. A staticmethod receives neither and is just a function placed in the class namespace for organisation.

  3. 3

    Explain @staticmethod, @classmethod and instance methods with an example.

    medium

    Instance methods operate on one object. A classmethod operates on the class, commonly as a factory, and respects subclasses because cls is whatever class it was called on. A staticmethod needs neither and cannot see the instance or class state unless you pass it in.

    python
    class Date:
        def __init__(self, y, m, d):
            self.y, self.m, self.d = y, m, d
        @classmethod
        def from_string(cls, s):
            return cls(*map(int, s.split("-")))
        @staticmethod
        def is_leap(y):
            return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)
    
    d = Date.from_string("2026-11-19")
    print(d.y, Date.is_leap(2024))   # 2026 True
  4. 4

    What is the method resolution order (MRO)? Predict this diamond output.

    medium

    The MRO is the linear order in which Python searches classes for an attribute, computed by the C3 linearisation algorithm. It keeps children before parents and preserves the order bases are listed. super() does not mean the parent: it means the next class in the MRO of the instance. With cooperative super() calls in a diamond, each class runs exactly once.

    python
    class A:
        def hi(self): print("A")
    class B(A):
        def hi(self): print("B"); super().hi()
    class C(A):
        def hi(self): print("C"); super().hi()
    class D(B, C):
        def hi(self): print("D"); super().hi()
    
    D().hi()                       # D B C A
    print([c.__name__ for c in D.__mro__])
    # ['D', 'B', 'C', 'A', 'object']
  5. 5

    What does __init__ do, and is it the constructor?

    easy

    __init__ initialises an object that already exists. The object is created by __new__, which allocates and returns the instance, and then Python calls __init__ on it. In day-to-day code you override __init__ only. You override __new__ for immutable subclasses such as a str or tuple subclass, or for singletons. __init__ must return None, otherwise a TypeError is raised.

  6. 6

    How does Python implement encapsulation? What is name mangling?

    medium

    Python relies on convention. A single leading underscore signals internal use. A double leading underscore without a trailing double underscore triggers name mangling: inside class Foo, __x is stored as _Foo__x, which avoids accidental clashes in subclasses. It is not security, since obj._Foo__x still works. For controlled access, use properties.

    python
    class Acct:
        def __init__(self): self.__bal = 10
    a = Acct()
    # a.__bal -> AttributeError
    print(a._Acct__bal)   # 10
    print([k for k in vars(a)])  # ['_Acct__bal']
  7. 7

    What is @property and why use it?

    medium

    A property exposes a method as an attribute, so callers write obj.area rather than obj.area(). With a setter you can validate on assignment. It lets you start with a plain attribute and later add logic without breaking callers, which is why Python code avoids Java-style getters and setters.

    python
    class Circle:
        def __init__(self, r): self.r = r
        @property
        def area(self): return 3.14159 * self.r ** 2
        @property
        def r(self): return self._r
        @r.setter
        def r(self, v):
            if v < 0: raise ValueError("negative radius")
            self._r = v
    
    c = Circle(2)
    print(round(c.area, 2))   # 12.57
  8. 8

    What is the difference between __str__ and __repr__?

    medium

    __repr__ returns an unambiguous developer-facing string, ideally one that could recreate the object. __str__ returns a readable string for end users. print() and str() use __str__, falling back to __repr__ if it is missing. Containers always use repr on their elements, and the REPL shows repr. If you define only one, define __repr__.

    python
    class P:
        def __repr__(self): return "P(1)"
    print(P())        # P(1)
    print([P()])      # [P(1)]
  9. 9

    What is the difference between method overloading and overriding in Python?

    medium

    Python does not support overloading by signature: if you define a method twice in a class, the later definition replaces the earlier. Emulate it with default arguments, *args, or functools.singledispatch. Overriding is supported: a subclass defines a method with the same name and its version is found first in the MRO. Use super() to extend rather than replace the parent behaviour.

  10. 10

    What are abstract base classes?

    medium

    An abstract base class, created with the abc module, declares methods that subclasses must implement. A class with unimplemented @abstractmethod members cannot be instantiated. It formalises an interface and gives early failure at instantiation instead of a late AttributeError.

    python
    from abc import ABC, abstractmethod
    class Shape(ABC):
        @abstractmethod
        def area(self): ...
    class Sq(Shape):
        def __init__(self, s): self.s = s
        def area(self): return self.s ** 2
    
    # Shape()  -> TypeError: Can't instantiate abstract class
    print(Sq(3).area())   # 9
  11. 11

    Predict the output: modifying a class attribute through the class and through an instance.

    hard

    Reading c.x finds the class attribute until an instance attribute with the same name exists. Assigning c.x = 2 creates an instance attribute that shadows the class one. After that, changing the class attribute no longer affects that instance, but it still affects instances that never assigned.

    python
    class C:
        x = 1
    a, b = C(), C()
    a.x = 2
    C.x = 3
    print(a.x, b.x, C.x)   # 2 3 3
  12. 12

    What is the difference between composition and inheritance, and when do you prefer composition?

    medium

    Inheritance models an is-a relationship and couples the subclass to the parent's implementation. Composition models has-a: an object holds other objects and delegates to them. Prefer composition when you only want to reuse behaviour, when the hierarchy would be deep, or when the behaviour may change at runtime. A Car that has an Engine is clearer than a Car that extends Engine.

  13. 13

    What are dunder methods? Name the ones that make an object behave like a container.

    medium

    Dunder, or magic, methods are special names with double underscores that Python calls on your behalf. For container behaviour implement __len__, __getitem__, __setitem__, __delitem__, __contains__ and __iter__. For operators, use __add__, __eq__, __lt__ and so on. With __eq__ defined and __lt__ added, functools.total_ordering can fill in the other comparisons.

    python
    class Deck:
        def __init__(self): self.c = [1, 2, 3]
        def __len__(self): return len(self.c)
        def __getitem__(self, i): return self.c[i]
    d = Deck()
    print(len(d), d[0], list(d), 2 in d)   # 3 1 [1, 2, 3] True
  14. 14

    What does __slots__ do?

    hard

    Declaring __slots__ = ('x', 'y') tells Python to store those attributes in fixed slots instead of a per-instance __dict__. This saves memory when you create millions of small objects and blocks creation of undeclared attributes. Costs: no dynamic attributes, no weak references unless __weakref__ is listed, and inheritance needs care because a subclass without __slots__ gets a __dict__ again.

  15. 15

    What is a metaclass?

    hard

    A metaclass is the class of a class. Normal classes are instances of type, and type(name, bases, namespace) creates a class dynamically. A custom metaclass, set with class C(metaclass=Meta), can intercept class creation to register subclasses, enforce rules or inject attributes. Most problems are solved more simply with class decorators or __init_subclass__, so interviewers mostly want to see that you know the idea exists.

    python
    class Meta(type):
        def __new__(m, name, bases, ns):
            ns["tag"] = name.lower()
            return super().__new__(m, name, bases, ns)
    class Thing(metaclass=Meta): pass
    print(Thing.tag)   # thing
  16. 16

    What is the difference between a dataclass and a regular class?

    medium

    The @dataclass decorator generates __init__, __repr__ and __eq__ from annotated fields, and optionally ordering, immutability with frozen=True, and slots=True. It removes boilerplate for classes that mostly hold data. For mutable defaults you must use field(default_factory=list), since a bare list default raises ValueError.

    python
    from dataclasses import dataclass, field
    @dataclass(order=True)
    class Item:
        name: str
        tags: list = field(default_factory=list)
    print(Item("a"))   # Item(name='a', tags=[])

Frequently asked questions

Does Python support multiple inheritance?

Yes. Classes can list several bases, and the C3 method resolution order decides which implementation wins. Use cooperative super() calls so each class in a diamond runs once.

Does Python have private variables?

Not enforced ones. A leading underscore is a convention and a double underscore triggers name mangling, which prevents accidental clashes but can still be bypassed.

What are the four pillars of OOP in Python terms?

Encapsulation through classes and properties, abstraction through ABCs, inheritance through subclasses and the MRO, and polymorphism through duck typing, where any object with the right methods works.

When should I use a dataclass?

When a class mainly stores fields and you want generated init, repr and equality. Use a normal class when behaviour and invariants dominate.

Related guides

More in Programming Language Interview Questions by Language

See all in this section