Interview Q&A · Python · 35 questions in this topic
Object-Oriented Python — Python Interview Q&A
Classes, objects, inheritance and the dunder protocol — including MRO, the diamond problem and how Python implements encapsulation without real access modifiers. Part of Object-Oriented Python · 375 questions in the Python bank.
What are classes and objects in Python?
Answer
A class is a blueprint that defines the structure (attributes) and behavior (methods) shared by a group of objects. An object (instance) is a concrete value created from that blueprint, with its own independent state.
In Python, classes themselves are also objects (instances of type), which is part of why Python's object model is considered unusually consistent — "everything is an object," including classes, functions, and modules.
Example
class Dog: def __init__(self, name): self.name = name # instance attribute def bark(self): return f"{self.name} says Woof!" rex = Dog("Rex") # rex is an object/instance of Dog fido = Dog("Fido") print(rex.bark()) # 'Rex says Woof!' print(fido.bark()) # 'Fido says Woof!' -- independent state print(type(rex)) # <class '__main__.Dog'> print(type(Dog)) # <class 'type'> -- classes are objects too
💡 Mentioning "classes are themselves instances of type " is a small detail that previews metaclass understanding and signals depth beyond textbook OOP definitions.
What is __init__, and when is it called?
Answer
__init__ is the initializer method, automatically called immediately after a new instance is created, used to set up that instance's initial state (its instance attributes).
__init__ is often mistakenly called "the constructor," but the actual object-creation step happens in __new__ (Q115) — __init__ just configures the already-created object. __init__ should not return anything other than None; returning any other value raises a TypeError.
Example
class User: def __init__(self, username, active=True): self.username = username self.active = active print(f"Creating user: {username}") u = User("ana") # prints "Creating user: ana" during construction print(u.username, u.active) # ana True
💡 If asked "is __init__ a constructor?", the precise answer is "not exactly — __new__ constructs the object, __init__ initializes it." Bringing this up unprompted is a strong depth signal.
What is the difference between instance variables and class variables?
Answer
An instance variable belongs to one specific object and is usually set in __init__ via self.x =. A class variable is shared by all instances of the class, defined directly in the class body outside any method.
Reading a class variable through an instance works fine (Python looks it up on the instance first, then falls back to the class). But assigning to self.attribute = value always creates a new instance variable that shadows the class variable for that object only — it does not modify the shared class variable.
Example
class Employee: company = "Acme Corp" # class variable -- shared by all instances def __init__(self, name): self.name = name # instance variable -- unique per object e1 = Employee("Ana") e2 = Employee("Ben") print(e1.company, e2.company) # Acme Corp Acme Corp -- shared Employee.company = "NewCo" # changes the shared class variable print(e1.company, e2.company) # NewCo NewCo -- both see the change e1.company = "Solo LLC" # creates a NEW instance variable on e1 only print(e1.company, e2.company) # Solo LLC NewCo -- e2 unaffected
What are instance methods?
Answer
An instance method is a regular method defined inside a class that takes self as its first parameter, giving it access to that specific instance's attributes and other methods.
Instance methods are the default and most common kind of method — they're what you're defining any time you write def method(self,.) inside a class without a @classmethod or @staticmethod decorator.
Example
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): # instance method -- needs self return self.width * self.height r = Rectangle(4, 5) print(r.area()) # 20 -- 'self' is implicitly r
💡 Tie this back to, Q79 — an instance method is exactly the "bound method" concept discussed there, applied specifically inside a class definition.
What are class methods, and when would you use @classmethod?
Answer
A class method receives the class itself (conventionally named cls) as its first argument instead of an instance, defined with the @classmethod decorator. They're most commonly used for alternative constructors.
Because a class method receives cls rather than a specific instance, it can be called on the class directly (ClassName.method()) without needing an existing object, and it correctly respects subclassing — if called on a subclass, cls refers to the subclass, not the original defining class.
Example
class Pizza: def __init__(self, toppings): self.toppings = toppings @classmethod def margherita(cls): # alternative constructor return cls(["tomato", "mozzarella"]) @classmethod def pepperoni(cls): return cls(["tomato", "mozzarella", "pepperoni"]) p = Pizza.margherita() # no need to build the list manually print(p.toppings) # ['tomato', 'mozzarella']
💡 "Alternative constructor" is the single most common real-world use case for @classmethod — have this exact pizza-style example (or an equivalent like from_json, from_config) ready to go.
What are static methods, and when would you use @staticmethod?
Answer
A static method takes neither self nor cls — it behaves like a plain function that happens to live inside the class's namespace, usually because it's logically related to the class but doesn't need access to instance or class state.
Use a static method purely for organizational/namespacing purposes: grouping a utility function with the class it's conceptually related to, without pretending it needs self or cls it doesn't actually use.
Example
class TemperatureConverter: @staticmethod def celsius_to_fahrenheit(c): return (c * 9 / 5) + 32 # Callable on the class directly, no instance needed, no self/cls involved print(TemperatureConverter.celsius_to_fahrenheit(100)) # 212.0
💡 If you find yourself writing a static method that secretly needs class or instance data, that's a sign it should be a class method or instance method instead — say this to show you understand why the choice matters, not just the syntax.
What is the difference between instance methods, class methods, and static methods?
Answer
They differ in what they automatically receive as their first argument: instance methods get self (the instance), class methods get cls (the class), and static methods get neither.
instance state? state?
Key points
- 1Decorator — Instance Method: none; Class Method: @classmethod; Static Method: @staticmethod
- 2First argument — Instance Method: self (the instance); Class Method: cls (the class); Static Method: none
- 3Can access — Instance Method: Yes; Class Method: No; Static Method: No
- 4Can access/ modify class — Instance Method: Yes (via self.__class__ or type(self)); Class Method: Yes, directly via cls; Static Method: No (would need explicit ClassName.attr)
- 5Typical use — Instance Method: Normal object behavior; Class Method: Alternative constructors, class-wide operations; Static Method: Utility functions grouped by relevance
Example
class Demo: class_data = "shared" def instance_method(self): return f"instance method, self.class_data = {self.class_data}" @classmethod def class_method(cls): return f"class method, cls.class_data = {cls.class_data}" @staticmethod def static_method(): return "static method, no access to class_data directly" d = Demo() print(d.instance_method()) # can reach class_data via self print(d.class_method()) # can reach class_data via cls print(d.static_method()) # no automatic access at all
💡 This comparison table question is often used as a "explain it in one sentence each" speed-check — practice giving crisp, one-line distinctions rather than long explanations for each.
What is encapsulation in Python, and how is it implemented?
Answer
Encapsulation means bundling data and the methods that operate on it together, while restricting direct outside access to some of that data. Python implements this through naming conventions (a single or double leading underscore) rather than strict compiler-enforced access control like private in Java or C++.
Python's philosophy is famously "we're all consenting adults here" — nothing is truly unreachable from outside a class; the underscore conventions communicate intent rather than enforcing a hard technical barrier.
Example
class BankAccount: def __init__(self, balance): self._balance = balance # "protected" by convention -- internal use def deposit(self, amount): if amount > 0: self._balance += amount def get_balance(self): return self._balance acc = BankAccount(100) acc.deposit(50) print(acc.get_balance()) # 150 print(acc._balance) # 150 -- still technically accessible! convention, not enforcement
💡 Contrast Python's convention-based approach directly with Java/C++'s enforced private keyword — this comparison is almost always what the interviewer is checking for when they ask about encapsulation "in Python" specifically.
What is the difference between public, protected, and private attributes in Python?
Answer
Public attributes (name) have no naming restriction and are meant for external use. A single leading underscore (_name) signals "internal use, please don't touch" purely by convention. A double leading underscore (__name) triggers actual name mangling, making accidental external access and subclass name collisions much less likely — though still not impossible.
Name mangling rewrites __name inside a class body to _ClassName__name internally, which is a real mechanism (not just convention), primarily intended to avoid attribute name clashes in inheritance hierarchies rather than to provide true security.
Example
class Base: def __init__(self): self.public = "anyone can read this" self._protected = "internal use, by convention" self.__private = "name-mangled" b = Base() print(b.public) # fine print(b._protected) # fine, just impolite # print(b.__private) # AttributeError! print(b._Base__private) # 'name-mangled' -- still reachable via the mangled name
💡 Emphasize that double-underscore name mangling exists mainly to prevent accidental collisions in inheritance, not to provide airtight security — Python has no true private attributes, and any interviewer testing this wants to hear that nuance.
What is name mangling in Python?
Answer
Name mangling automatically rewrites any identifier of the form __spam (two leading underscores, at most one trailing underscore) used inside a class body into _ClassName__spam, to reduce accidental attribute name clashes between a base class and its subclasses.
Without mangling, a subclass defining its own __private attribute with the same name as one in a parent class could silently and dangerously collide with the parent's internal implementation detail. Mangling makes each class's "private" attributes namespaced under that class's own name.
Example
class Parent: def __init__(self): self.__secret = "parent's secret" # becomes _Parent__secret def reveal(self): return self.__secret # Python rewrites this too, automatically class Child(Parent): def __init__(self): super().__init__() self.__secret = "child's own secret" # becomes _Child__secret -- no collision! c = Child() print(c.reveal()) # "parent's secret" -- Parent's method sees its own mangled attribute print(c._Parent__secret) # "parent's secret" print(c._Child__secret) # "child's own secret"
💡 Show, don't just tell — walking through the Parent / Child example above to demonstrate that both __secret attributes coexist without colliding is far more convincing than reciting the definition.
What is inheritance in Python?
Answer
Inheritance lets a class (the subclass/child) acquire the attributes and methods of another class (the superclass/ parent), enabling code reuse and the modeling of "is-a" relationships. In Python, it's declared by listing the parent class in parentheses after the class name.
A subclass can use parent methods unchanged, override them entirely, or extend them (calling the parent's version via super() and adding more behavior). Every class in Python implicitly inherits from object if no other base class is specified.
Example
class Animal: def __init__(self, name): self.name = name def speak(self): return f"{self.name} makes a sound" class Dog(Animal): # Dog inherits from Animal def speak(self): # override return f"{self.name} barks" class Cat(Animal): pass # inherits speak() unchanged print(Dog("Rex").speak()) # 'Rex barks' print(Cat("Tom").speak()) # 'Tom makes a sound' -- inherited, not overridden
💡 Mention that every class implicitly inherits from object — it's a small fact that connects naturally to later questions about dunder methods and the MRO.
What is multiple inheritance, and how does Python handle it?
Answer
Multiple inheritance lets a class inherit from more than one parent class simultaneously. Python explicitly supports this (unlike Java, which only allows multiple interface inheritance), resolving any ambiguity about which parent's method to use via the Method Resolution Order (MRO — Q94).
Multiple inheritance is powerful but can quickly become confusing if the parent classes have overlapping method names or complex hierarchies. It's most cleanly used with small, focused "mixin" classes (Q114) rather than large, complex base classes.
Example
class Swimmer: def move(self): return "swimming" class Flyer: def move(self): return "flying" class Duck(Swimmer, Flyer): # inherits from both pass d = Duck() print(d.move()) # 'swimming' -- Swimmer comes first in the inheritance list print(Duck.__mro__) # shows the exact lookup order Python used
💡 If two parent classes define the same method, the result depends entirely on the order they're listed in the class definition — always be ready to explain "why swimming and not flying" using MRO, not just guess.
What is the diamond problem, and how does Python resolve it?
Answer
The diamond problem occurs when two classes both inherit from a common base class, and a fourth class inherits from both of them — creating ambiguity about which path to the shared base class should be used. Python resolves this deterministically using the C3 linearization algorithm to compute a single, consistent MRO.
The "diamond" shape refers to the inheritance diagram: D inherits from B and C, both of which inherit from A. Naively, it's unclear whether D 's lookup of a method defined only on A should go through B first or C first, or whether A 's __init__ might run twice.
C3 linearization guarantees a single consistent order that respects both the order parents are listed and the requirement that a class always appears before its own parents in the resolution order.
Example
class A: def greet(self): return "Hello from A" class B(A): def greet(self): return "Hello from B" class C(A): def greet(self): return "Hello from C" class D(B, C): # diamond: D -> B -> A and D -> C -> A pass print(D().greet()) # 'Hello from B' -- follows the MRO, not naive left-to-right guessing print([c.__name__ for c in D.__mro__]) # ['D', 'B', 'C', 'A', 'object']
💡 Draw (or describe) the diamond shape explicitly when answering — interviewers want to see that you visualize the actual inheritance graph, not just recite "C3 linearization" as a buzzword.
What is MRO (Method Resolution Order), and how is it computed?
Answer
MRO is the specific, deterministic order Python searches through a class's ancestors when looking up a method or attribute. Since Python 2.3, it's computed using the C3 linearization algorithm, viewable at any time via ClassName.__mro__ or ClassName.mro().
C3 linearization guarantees three properties: a subclass always comes before its parents, the order of parents as declared in the class statement is preserved, and the algorithm is monotonic (consistent across the whole hierarchy — if it works for a class, it keeps working the same way for its subclasses).
Example
class A: pass class B(A): pass class C(A): pass class D(B, C): pass print(D.__mro__) # (<class 'D'>, <class 'B'>, <class 'C'>, <class 'A'>, <class 'object'>) print(D.mro()) # same information, as a list instead of a tuple
💡 " __mro__ shows the exact search order Python will use for every method/attribute lookup on this class" is the one-sentence explanation that ties MRO's abstract definition to something concretely useful in debugging.
What does super() do, and how does it work with the MRO?
Answer
super() returns a proxy object that lets you call a method from the next class in the current instance's MRO — not necessarily the immediate parent class as written in the source, but whichever class comes next according to the fully resolved MRO.
This distinction matters enormously in multiple inheritance: super() in a class B doesn't always mean "call A 's version" — it means "call whatever comes after B in this particular instance's MRO," which could be a different class entirely depending on the full hierarchy the instance was built from.
Example
class A: def greet(self): print("A.greet") class B(A): def greet(self): print("B.greet") super().greet() # goes to "next in MRO," not necessarily A directly class C(A): def greet(self): print("C.greet") super().greet() class D(B, C): def greet(self): print("D.greet") super().greet() D().greet() # D.greet # B.greet # C.greet <- super() in B goes to C, not directly to A! # A.greet
What is polymorphism in Python?
Answer
Polymorphism means objects of different classes can be used interchangeably through a shared interface, as long as they implement the expected methods — the same code (shape.area()) works correctly regardless of the specific underlying class.
Python's polymorphism is largely enabled by dynamic typing and duck typing (Q99): the language doesn't check that an object is a specific type before calling a method on it, only that the method exists and works — "if it walks like a duck and quacks like a duck."
Example
class Circle: def __init__(self, radius): self.radius = radius def area(self): return 3.14159 * self.radius ** 2 class Square: def __init__(self, side): self.side = side def area(self): return self.side ** 2 shapes = [Circle(3), Square(4)] for shape in shapes: print(shape.area()) # same call, different behavior per object -- polymorphism
💡 Note that these two classes don't even share a common parent class here — Python's polymorphism doesn't strictly require inheritance, just a matching interface. This connects directly to duck typing (Q99).
What is method overriding?
Answer
Method overriding is when a subclass defines a method with the same name as one in its parent class, replacing (or extending, via super()) the parent's behavior for instances of the subclass.
Overriding is how polymorphism is typically implemented across a class hierarchy — the calling code stays the same, but which version of the method actually runs depends on the object's real (runtime) class, not the type of the variable referencing it.
Example
class Employee: def calculate_bonus(self, salary): return salary * 0.10 class Manager(Employee): def calculate_bonus(self, salary): # overrides the parent version base = super().calculate_bonus(salary) # can still call the parent's version return base + 500 print(Employee().calculate_bonus(1000)) # 100.0 print(Manager().calculate_bonus(1000)) # 600.0 -- extends, doesn't just replace
💡 Distinguish "overriding" (replacing the method entirely) from "extending" (calling super() and adding to it) explicitly — both are valid overriding techniques, and knowing when to use each shows design maturity.
Does Python support method overloading? How do you simulate it?
Answer
Not in the traditional sense (multiple methods with the same name but different parameter signatures, resolved at compile time, as in Java or C++). Python only keeps the last definition of a method with a given name — earlier ones are silently overwritten. Overloading-like behavior is simulated using default arguments, *args / **kwargs, or type checks inside a single method.
This is a direct consequence of Python being dynamically typed and not distinguishing methods by parameter type at definition time — there's simply no mechanism to have two methods share a name in the same class.
Example
class Calculator: # This second definition SILENTLY REPLACES the first -- no error, no overload! def add(self, a, b): return a + b def add(self, a, b, c): # only this version actually exists now return a + b + c calc = Calculator() # calc.add(1, 2) # TypeError: missing 1 required positional argument: 'c' # Simulated "overloading" with default arguments: class BetterCalculator: def add(self, a, b, c=0): return a + b + c better = BetterCalculator() print(better.add(1, 2)) # 3 print(better.add(1, 2, 3)) # 6
What is duck typing, and how does it relate to polymorphism?
Answer
Duck typing means Python cares about whether an object behaves correctly (has the methods/attributes being used) rather than what its declared type is — "if it walks like a duck and quacks like a duck, it's treated as a duck," regardless of its actual class or inheritance.
This is what allows Q96's polymorphism example to work even though Circle and Square share no common base class — Python never checks isinstance() before calling.area(), it just tries to call it and either succeeds or raises AttributeError at runtime.
Example
class Duck: def quack(self): return "Quack!" class Person: def quack(self): return "I'm imitating a duck!" def make_it_quack(thing): return thing.quack() # no type check at all -- just tries calling .quack() print(make_it_quack(Duck())) # 'Quack!' print(make_it_quack(Person())) # "I'm imitating a duck!" -- works, unrelated classes
💡 Duck typing is why Python favors "ask forgiveness, not permission" (EAFP, try/except) over "look before you leap" (LBYL, isinstance() checks) as an idiom — mentioning this connects OOP philosophy to Python's broader coding style.
What are abstract classes in Python?
Answer
An abstract class defines a common interface that subclasses are required to implement, but cannot be instantiated directly itself. Python implements this via the abc module's ABC base class and the @abstractmethod decorator.
Abstract classes are useful when you want to guarantee that every subclass implements certain methods, catching the mistake of forgetting to do so at instantiation time rather than with a confusing AttributeError deep in unrelated code later.
Example
from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass # no implementation -- subclasses MUST provide one class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14159 * self.radius ** 2 # shape = Shape() # TypeError: Can't instantiate abstract class Shape circle = Circle(5) # fine -- implements the required area() print(circle.area()) # 78.53975
💡 If you forget to implement area() in Circle, Python raises the TypeError at instantiation time, not when.area() is finally called — mention that this "fail fast" behavior is the core value abstract classes add over plain documentation.
What is the abc module, and how do you use it?
Answer
abc (Abstract Base Classes) is the standard library module providing the infrastructure for defining abstract classes: the ABC base class (or ABCMeta metaclass) and the @abstractmethod decorator that marks methods subclasses must override.
Beyond @abstractmethod, the module also supports @abstractproperty -style patterns (via @property combined with @abstractmethod) and register(), which lets you declare that an unrelated class should be treated as a "virtual subclass" for isinstance() checks, without actually inheriting from it.
Example
from abc import ABC, abstractmethod class Serializer(ABC): @abstractmethod def serialize(self) -> str: ... @property @abstractmethod def format_name(self) -> str: ... class JSONSerializer(Serializer): def serialize(self): return "{...}" @property def format_name(self): return "json" s = JSONSerializer() print(s.serialize(), s.format_name) # {...} json
💡 Mention Serializer.register(SomeUnrelatedClass) as an advanced feature if the conversation goes deep — it shows awareness that Python's ABCs can support duck-typing-style "virtual" inheritance, not just strict class hierarchies.
Why use an abstract base class instead of just documenting an expected interface?
Answer
An abstract base class enforces the contract at instantiation time with a clear error message, rather than relying on developers reading (and remembering) documentation — mistakes surface immediately instead of causing confusing runtime failures much later in unrelated code.
This is a "fail fast" design principle: catching a missing implementation the moment a class is defined/instantiated is far cheaper to debug than discovering it when some deeply nested code finally calls the missing method and raises an unrelated-looking AttributeError.
Example
# Without ABC: relies purely on documentation and discipline class PluginBase: """Subclasses must implement run().""" # easy to miss or ignore pass class BrokenPlugin(PluginBase): pass # "forgot" to implement run() -- no error until it's actually called # With ABC: the mistake is caught immediately from abc import ABC, abstractmethod class Plugin(ABC): @abstractmethod def run(self): ... # class BrokenPlugin2(Plugin): pass # BrokenPlugin2() # TypeError immediately -- can't even create the object
💡 Frame this as a "fail fast vs fail late" trade-off — abstract base classes trade a small amount of upfront ceremony for much earlier, clearer error messages across a team or plugin-style codebase.
What are properties in Python (@property)?
Answer
@property lets you define a method that's accessed like a plain attribute (no parentheses), enabling computed values or validation logic to run transparently behind what looks like simple attribute access.
This lets you start with plain public attributes and later add validation or computed logic without breaking the existing public interface — callers keep writing obj.value, unaware that a method is now running behind the scenes.
Example
class Circle: def __init__(self, radius): self.radius = radius @property def area(self): # accessed as .area, not .area() return 3.14159 * self.radius ** 2 c = Circle(4) print(c.area) # 50.26544 -- looks like an attribute, is actually a method call
💡 "Properties let you change your implementation later without changing your public API" is the key design justification interviewers want — not just "it's a decorator that makes a method look like an attribute."
How do you implement getters and setters in Python?
Answer
The Pythonic approach is to start with plain public attributes, and only introduce @property (getter) plus @x.setter (setter) later, if and when you actually need validation or computed logic — not to write Java-style get_x() / set_x() methods from the very beginning.
This is a genuine philosophical difference from Java/C++ conventions: Python developers are encouraged to avoid boilerplate getters/setters entirely until there's a real reason for them, because @property lets you upgrade a plain attribute to validated logic later without ever changing the calling code.
Example
class Product: def __init__(self, price): self._price = price @property def price(self): # getter return self._price @price.setter def price(self, value): # setter -- validation lives here if value < 0: raise ValueError("Price cannot be negative") self._price = value p = Product(100) p.price = 150 # calls the setter transparently print(p.price) # calls the getter transparently -> 150 # p.price = -10 # raises ValueError
What are magic (dunder) methods in Python?
Answer
Magic methods (also called "dunder" methods, for double underscore) are special methods with names like __init__, __str__, and __add__ that Python calls automatically in response to built-in operations — object creation, string conversion, operators, and more. Collectively, they define Python's "data model."
Implementing the right dunder methods is what lets your custom classes integrate seamlessly with Python's built-in syntax and functions — supporting +, len(), in, indexing (obj[key]), iteration, comparisons, and more, exactly like built-in types do.
Example
class Money: def __init__(self, amount): self.amount = amount def __add__(self, other): # enables the + operator return Money(self.amount + other.amount) def __repr__(self): # enables meaningful printing return f"Money({self.amount})" a = Money(10) b = Money(5) print(a + b) # Money(15) -- '+' works because of __add__
💡 Framing dunder methods as "how you opt your own class into Python's built-in syntax" is a cleaner explanation than listing them individually — it explains why they exist, not just what they're named.
What is the difference between __str__ and __repr__?
Answer
__str__ should return a readable, user-facing description (used by print() and str()). __repr__ should return an unambiguous, developer-facing representation — ideally one that could recreate the object if passed back to eval(). If __str__ isn't defined, Python falls back to __repr__.
A commonly cited guideline: __repr__ is for developers (shown in the interactive shell, in debuggers, inside a list's printed representation), while __str__ is for end users. If you can only implement one, implement __repr__ — it's used as the fallback for __str__ and is also what shows up when printing objects nested inside containers like lists.
Example
class Point: def __init__(self, x, y): self.x, self.y = x, y def __repr__(self): return f"Point(x={self.x}, y={self.y})" # unambiguous, debug-friendly def __str__(self): return f"({self.x}, {self.y})" # friendly, for end users p = Point(1, 2) print(p) # (1, 2) -- uses __str__ print(repr(p)) # Point(x=1, y=2) -- uses __repr__ print([p]) # [Point(x=1, y=2)] -- lists always use __repr__ for their contents
💡 "Lists print their contents using repr(), not str() " is a small, precise detail that trips up candidates who only implemented __str__ and can't explain why a list of their objects looks wrong.
How do __eq__ and __hash__ interact when defined on a custom class?
Answer
__eq__ defines what == means for your objects; __hash__ defines what value is used when your object is placed in a set or used as a dict key. If you define __eq__ without also defining __hash__, Python automatically makes your class unhashable — because it can no longer guarantee the hash/equality consistency contract from Q43.
The rule (from, Q43) is: equal objects must have equal hashes. Python enforces the "safe default" of removing __hash__ entirely when you override __eq__, rather than risk silently violating that contract with the inherited identity-based hash.
Example
class Version: def __init__(self, major, minor): self.major, self.minor = major, minor def __eq__(self, other): return (self.major, self.minor) == (other.major, other.minor) # No __hash__ defined! v1 = Version(1, 0) v2 = Version(1, 0) print(v1 == v2) # True -- __eq__ works fine # print({v1, v2}) # TypeError: unhashable type -- __hash__ was set to None automatically class VersionFixed: def __init__(self, major, minor): self.major, self.minor = major, minor def __eq__(self, other): return (self.major, self.minor) == (other.major, other.minor) def __hash__(self): return hash((self.major, self.minor)) # must be consistent with __eq__ vf1, vf2 = VersionFixed(1, 0), VersionFixed(1, 0) print({vf1, vf2}) # works, and correctly deduplicates to one item
What are __len__, __getitem__, __setitem__, and __contains__ used for?
Answer
These dunder methods let a custom class behave like a built-in container: __len__ powers len(obj), __getitem__ / __setitem__ power obj[key] read/write access (and, notably, basic iteration and slicing if written generally enough), and __contains__ powers the in operator.
Implementing just these few methods lets a custom class participate naturally in idiomatic Python code — for loops, in checks, indexing — without users needing to know it isn't a "real" built-in type underneath.
Example
class Inventory: def __init__(self): self._items = {} def __len__(self): return len(self._items) def __getitem__(self, key): return self._items[key] def __setitem__(self, key, value): self._items[key] = value def __contains__(self, key): return key in self._items inv = Inventory() inv["apples"] = 10 # uses __setitem__ print(inv["apples"]) # uses __getitem__ -> 10 print(len(inv)) # uses __len__ -> 1 print("apples" in inv) # uses __contains__ -> True
💡 Point out that implementing __getitem__ alone (accepting sequential integer indices starting at 0) is actually enough to make an object iterable, even without a formal __iter__ — Python falls back to trying indices 0, 1, 2. until an IndexError. This is a nice "hidden depth" fact for a strong answer.
What is __call__, and when would you use it?
Answer
__call__ lets an instance of a class be invoked like a function, using regular parentheses syntax: instance(args). It's commonly used to create objects that behave like configurable, stateful functions.
This pattern is especially useful when a callable needs to carry persistent configuration or state between calls — an alternative to closures that some developers find clearer when the state is more substantial or needs its own methods.
Example
class Multiplier: def __init__(self, factor): self.factor = factor def __call__(self, x): return x * self.factor double = Multiplier(2) print(double(5)) # 10 -- calling the instance directly, like a function print(callable(double)) # True -- because __call__ is defined # Practical use: a stateful callback that also tracks how many times it's run class CallCounter: def __init__(self): self.count = 0 def __call__(self, *args, **kwargs): self.count += 1 print(f"Called {self.count} times") counter = CallCounter() counter(); counter() # "Called 1 times" then "Called 2 times"
💡 Compare __call__ -based classes directly to closures — both let you create "functions with memory," but a __call__ class is often clearer when the state needs multiple related methods, not just one function's worth of behavior.
What is __del__, and why is it rarely used?
Answer
__del__ is the destructor, called when an object is about to be garbage collected. It's rarely used in practice because its exact timing is unpredictable (especially with reference cycles) and context managers (with blocks, __enter__ / __exit__) are almost always a more reliable way to guarantee cleanup.
Since CPython primarily uses reference counting, __del__ often does run promptly when an object's reference count hits zero — but this isn't guaranteed by the language, cyclic references delay it until the cyclic garbage collector runs, and exceptions raised inside __del__ are effectively swallowed (only printed to stderr), making it a poor place for critical cleanup logic like closing files or releasing locks.
Example
class Resource: def __init__(self, name): self.name = name print(f"Acquiring {name}") def __del__(self): print(f"Cleaning up {self.name}") # timing not guaranteed! r = Resource("file handle") del r # likely triggers __del__ immediately in CPython... but not guaranteed # Much more reliable pattern: a context manager class ManagedResource: def __enter__(self): print("Acquiring") return self def __exit__(self, exc_type, exc_val, exc_tb): print("Releasing") # guaranteed to run, even if an exception occurs with ManagedResource(): print("Using resource")
What is operator overloading in Python?
Answer
Operator overloading means defining how built-in operators (+, -, ==, <, etc.) behave for your own custom class, by implementing the corresponding dunder methods (__add__, __sub__, __eq__, __lt__, and so on).
This is a specific application of the broader dunder-method system covered in Q105–108 — the operators you can overload map directly onto specific special method names, documented as part of Python's data model.
Example
class Vector: def __init__(self, x, y): self.x, self.y = x, y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __eq__(self, other): return (self.x, self.y) == (other.x, other.y) def __repr__(self): return f"Vector({self.x}, {self.y})" v1 = Vector(1, 2) v2 = Vector(3, 4) print(v1 + v2) # Vector(4, 6) -- '+' calls __add__ print(v1 == Vector(1, 2)) # True -- '==' calls __eq__
💡 If asked to implement a custom class that supports comparisons (<, <=, >, >=), mention functools.total_ordering — it lets you define just __eq__ and one ordering method (like __lt__), and derives the rest automatically.
What is the risk of using a mutable class variable as a default value?
Answer
A mutable class variable (like a list or dict defined directly in the class body) is shared by every instance. If any instance mutates it in place rather than reassigning it, every other instance — and the class itself — sees that same change, since there's only ever one underlying object.
This is the class-level cousin of the mutable default argument trap from, and it's caused by the exact same underlying principle: the object is created once, and merely referenced (not copied) by every instance that hasn't shadowed it with its own instance attribute.
Example
class ShoppingCart: items = [] # BUG: shared across every single instance! def add_item(self, item): self.items.append(item) cart1 = ShoppingCart() cart2 = ShoppingCart() cart1.add_item("apple") print(cart2.items) # ['apple'] -- leaked into cart2! definitely not intended # Correct fix: create a fresh list per instance, inside __init__ class ShoppingCartFixed: def __init__(self): self.items = [] # instance attribute -- unique per object def add_item(self, item): self.items.append(item) c1, c2 = ShoppingCartFixed(), ShoppingCartFixed() c1.add_item("apple") print(c2.items) # [] -- correctly independent
What is the difference between composition and inheritance?
Answer
Inheritance models an "is-a" relationship (a Car is a Vehicle) by extending a base class. Composition models a "has-a" relationship (a Car has an Engine) by holding an instance of another class as an attribute and delegating to it. The common guidance is "favor composition over inheritance" for flexibility.
Inheritance creates tight coupling — a subclass is deeply bound to its parent's implementation details, and changes to the parent can unexpectedly break subclasses ("the fragile base class problem").
Composition is more flexible: you can swap out a composed component at runtime, combine multiple independent behaviors without navigating a complex hierarchy, and avoid the diamond-problem complexities of multiple inheritance entirely.
Example
# Inheritance: "is-a" class Vehicle: def move(self): return "moving" class Car(Vehicle): # a Car IS-A Vehicle pass # Composition: "has-a" class Engine: def start(self): return "engine started" class Car2: def __init__(self): self.engine = Engine() # a Car2 HAS-A Engine def start(self): return self.engine.start() # delegates to the composed object print(Car2().start()) # 'engine started'
💡 "Favor composition over inheritance" is a well-known design principle to cite, but back it up with a concrete reason — swapping implementations at runtime, or avoiding deep/fragile hierarchies — rather than stating the slogan alone.
What are mixins in Python?
Answer
A mixin is a small class designed to be combined with others via multiple inheritance, providing one specific, selfcontained piece of reusable functionality — it's not meant to be instantiated or used on its own.
Mixins are the "responsible" way to use multiple inheritance: instead of combining large, complex classes (which risks diamond-problem confusion), you combine several small, focused mixins that each do exactly one thing, keeping the resulting MRO easy to reason about.
Example
class JSONSerializableMixin: def to_json(self): import json return json.dumps(self.__dict__) class ComparableMixin: def __eq__(self, other): return self.__dict__ == other.__dict__ class User(JSONSerializableMixin, ComparableMixin): def __init__(self, name, age): self.name, self.age = name, age u = User("Ana", 30) print(u.to_json()) # '{"name": "Ana", "age": 30}' print(u == User("Ana", 30)) # True -- via ComparableMixin
💡 Naming Django's LoginRequiredMixin or similar framework mixins (if you've used one) makes this answer concrete and grounded in real experience rather than abstract theory.
What is the difference between __new__ and __init__?
Answer
__new__ is the method that actually creates and returns a new instance (it's a static method, technically); __init__ then initializes that already-created instance's state. __new__ runs first, and its return value is what gets passed to __init__ as self.
You almost never need to override __new__ in everyday application code — __init__ is sufficient for the vast majority of use cases. __new__ matters when you need to control the object creation process itself, such as implementing immutable types (subclassing tuple or str) or the singleton pattern, where you need to potentially return an existing instance instead of always creating a new one.
Example
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: print("Creating the one and only instance") cls._instance = super().__new__(cls) return cls._instance def __init__(self, value): # NOTE: __init__ still runs every time Singleton(...) is called, # even when __new__ returns the same cached instance! self.value = value a = Singleton(1) b = Singleton(2) print(a is b) # True -- same object print(a.value) # 2 -- __init__ ran again and overwrote it
Recommended resourcesAffiliate links · may earn us a commission