🐍 Python for Everyone

← Back to challenges

Chapter 15 Interview Prep 25 min read

Interview Questions: OOP Deeper

Once a candidate can build a plain class, interviewers probe for the finer control that separates "wrote a class" from "designs a class's public interface deliberately." This set covers @staticmethod vs. @classmethod vs. a regular instance method and what each receives as its first parameter, why @classmethod is the standard pattern for alternative constructors, single vs. double underscore naming and what name mangling actually does, Python's "we're all consenting adults" privacy philosophy, and why @property is preferred over explicit get_x()/set_x() methods — including the real-world scenario of upgrading a plain public attribute to a property later without breaking any calling code.

1 What's the actual difference between a regular instance method, a @classmethod, and a @staticmethod?

The difference is entirely about what gets automatically passed in as the first parameter. A regular instance method automatically receives self — the specific object it was called on — so it can read and change that object's own instance attributes. A @classmethod automatically receives cls — the class itself, not any particular instance — so it can read or use class-level data and, most commonly, build and return a new instance of that class. A @staticmethod receives neither self nor cls automatically — it behaves like a plain function that just happens to live inside the class's namespace for organizational purposes, with no automatic access to any particular instance's data or the class itself. Reach for an instance method when the logic needs a specific object's data, a classmethod when the logic needs the class itself (most often to build an instance a different way), and a staticmethod when the logic is just related to the class conceptually but needs no instance or class data at all — a pure utility/helper function that could live outside the class but reads more clearly grouped inside it.

Not knowing which of self/cls/neither each decorator's method automatically receives, or being unable to give a concrete reason to pick one over another beyond "they're just different decorators."

"Inside a @classmethod named from_string, can that method access a specific existing instance's own instance attribute directly, the way an ordinary instance method could with self.something?" (No — a classmethod only automatically receives cls, the class itself, not any particular instance; it has no self to work with unless one is separately passed in as a normal argument.)

2 Why is @classmethod the standard pattern for an "alternative constructor," rather than just writing a second regular method?

An alternative constructor is a method that builds and returns a brand-new instance of the class, but starting from different input than __init__ expects — for example, building a BankAccount from a single formatted string instead of separate arguments. A @classmethod is the right tool because it automatically receives cls — the actual class it was called on — and can then call cls(...) internally to construct and return a new instance, without ever hard-coding the class's literal name inside the method body. That might sound like a minor detail, but it matters for a genuinely practical reason: if the class is ever renamed, or if this pattern is reused in a design where a method needs to work correctly across a family of related classes, cls(...) automatically refers to whichever class the method was actually called through, while a hard-coded BankAccount(...) inside a plain method would need to be manually updated everywhere. The conventional call site reads naturally too — BankAccount.from_string(data) — clearly signaling "this builds a new account, just from different raw input than the usual constructor call."

Writing an alternative constructor as a @staticmethod that hard-codes the class name inside instead of using cls(...), or not being able to explain why cls(...) is preferred over spelling out the class name literally.

"Inside a @classmethod named open_new_account, what expression actually creates and returns the new instance?" (return cls(...) with whatever arguments __init__ needs — cls refers to the class the method was called on, e.g. BankAccount, so cls(...) is equivalent to calling BankAccount(...) but without hard-coding that name inside the method.)

3 What's the difference between a single leading underscore like _balance and a double leading underscore like __balance?

A single leading underscore, _balance, is a convention only — it signals to other developers "this is an internal detail, please don't touch it directly from outside the class," but Python enforces absolutely nothing about it; code outside the class can still read or write account._balance freely, and nothing breaks at the language level. A double leading underscore, __balance, triggers name mangling: Python automatically rewrites that attribute's actual stored name behind the scenes to _ClassName__balance (e.g. _BankAccount__balance), which makes it awkward, though still not impossible, to access accidentally from outside the class. The practical distinction: single underscore is a polite "internal use" signal relied on entirely by convention and discipline; double underscore adds a real (if modest) technical obstacle on top of that same signal, primarily to avoid accidental name collisions in more complex class hierarchies.

Claiming __balance makes an attribute "truly private" and impossible to access from outside the class (it doesn't — it's still reachable, just under a mangled name), or treating single and double underscore as functionally identical.

"If a class named BankAccount sets self.__balance = 100 inside __init__, what is the actual attribute name Python stores that value under?" (_BankAccount__balance — Python automatically mangles any double-leading-underscore name defined inside a class body into _ClassName__name, which is why account.__balance from outside the class raises an AttributeError even though the data is still technically there under the mangled name.)

4 What does "name mangling" actually do to __balance, mechanically?

The moment Python compiles a class body and sees an attribute name starting with two leading underscores and at most one trailing underscore — like self.__balance written anywhere inside class BankAccount: — it automatically rewrites that name to self._BankAccount__balance, splicing in a single leading underscore plus the class's own name. This rewriting happens purely at compile time, based on textual scoping (which class body the code was written inside), not at runtime and not based on which object actually calls it. The practical effect is that self.__balance and account.__balance stop being the same lookup from outside the class: code inside BankAccount referring to self.__balance is automatically translated to the mangled name and works fine, but code outside the class trying account.__balance directly is looking for a plain __balance attribute that was never actually created under that exact name — it was stored as _BankAccount__balance instead — so that outside access raises an AttributeError.

Describing name mangling as happening at runtime based on the calling object, or not knowing that the mangled name specifically incorporates the class's own name.

"Can code outside the class still reach the value at all, even after mangling?" (Yes — nothing is truly hidden; account._BankAccount__balance from outside the class reaches the exact same value, since mangling only changes the stored name, not actual enforced access control; it discourages accidental access far more than it prevents deliberate access.)

5 Python is famous for having "no truly private attributes" compared to languages like Java. What's the philosophy behind that design choice?

This is often summarized as Python's "we're all consenting adults" philosophy: rather than the language mechanically locking a class's internals away from the outside world the way private does in Java or C++, Python relies on naming conventions (_x, __x) as clear signals of intent, trusting other developers to respect those signals rather than forcing the compiler to enforce them. The underlying reasoning is pragmatic — real enforced privacy occasionally gets in the way of legitimate needs, like debugging a third-party library's internals, monkey-patching in a test, or working around a genuine bug in code you can't immediately fix — and Python's designers chose to trust developers with that flexibility rather than block it outright. This doesn't mean privacy conventions don't matter in Python; a leading underscore is a real, meaningful signal that "this is an implementation detail, changing it isn't part of the class's guaranteed public contract" — it just means that signal is enforced by team discipline and code review, not by the interpreter refusing to run the code.

Claiming Python has no privacy concept at all (the naming conventions are a real, meaningful part of the language's culture, just not compiler-enforced), or claiming other languages' private keyword is somehow pointless by comparison rather than a legitimate different design trade-off.

"If Python attributes aren't truly enforced as private, what's the actual practical benefit of writing _balance instead of just balance?" (It's a clear, conventional signal to every other developer reading or using the class that this attribute is an internal implementation detail not meant to be relied on directly from outside — it won't stop anyone from accessing it, but it does communicate "this could change without notice, use the class's public methods/properties instead.")

6 Why is @property generally preferred over writing explicit get_balance()/set_balance() methods, the way many other languages do?

@property lets a class run real code (validation, computed values, logging) behind what still looks and reads like plain attribute access at the call site — account.balance instead of account.get_balance(), and account.balance = 500 instead of account.set_balance(500). This matters for real readability: a program that reads and writes an object's data constantly stays clean and natural-looking (account.balance everywhere) rather than being cluttered with parentheses on every single access, while still gaining every benefit of a method running underneath — a @property getter can compute a value on the fly instead of storing it, and a @x.setter can validate or transform an incoming value before it's actually stored. The other major advantage is evolution over time: a class can start with a plain public attribute, and later upgrade it to a @property with real validation logic, without changing a single line of code anywhere else that already uses account.balance — the call site's syntax never has to change, because attribute-style access is exactly what a property preserves.

Claiming @property is "just syntax sugar with no real benefit," or missing the key practical advantage that it preserves plain attribute-style syntax at every call site while still running real code underneath.

"If a class exposes balance as a @property instead of a method, does code elsewhere that reads account.balance need parentheses, like account.balance()?" (No — a @property-decorated method is accessed exactly like a plain attribute, with no parentheses at all; adding parentheses would actually be a bug, since account.balance already returns the computed/stored value directly.)

7 How does a @property setter enable validation without changing the class's public interface?

A @x.setter-decorated method runs automatically every single time code does obj.x = something, anywhere in the program — that assignment isn't a plain attribute write anymore, it's a real method call under the hood, which means the setter's body gets a chance to inspect the incoming value before anything is actually stored. A setter like @balance.setter def balance(self, value): if value < 0: raise ValueError(...) can reject an invalid value outright (raising an exception, refusing the assignment) instead of silently letting self.balance become something nonsensical like a negative amount of money. Critically, none of this changes what the assignment looks like from the outside — account.balance = 500 is still exactly how a caller sets the balance, whether that assignment quietly stores the value directly or, underneath, routes through a validating setter that could reject it. That's what makes properties powerful for real class design: the enforcement logic lives entirely inside the class, invisible to (and not requiring any change from) every piece of calling code that was already written before the validation was added.

Thinking a setter needs to be called with explicit method-call syntax like account.set_balance(500), or not recognizing that raising an exception inside a setter is exactly how it rejects an invalid assignment.

"With a @balance.setter that raises ValueError on a negative value, what happens when code runs account.balance = -50?" (The assignment triggers the setter method, which checks -50 < 0, finds it True, and raises ValueError immediately — self.balance is never actually set to -50; the previous valid value remains unchanged unless the caller catches the exception and handles it.)

8 A class currently exposes balance as a plain public attribute, and there's already calling code all over a large program doing account.balance = new_value. How do you add validation later without breaking that existing code? Why is this a genuinely common real interview question?

This is exactly the scenario @property is designed to solve, and it's a real, common situation because APIs and classes evolve — a class often starts simple (a plain attribute) before some bug or requirement reveals a need for validation, and by that point dozens of call sites already assume plain attribute syntax. The fix: rename the plain attribute to something internal like self._balance, then add a @property def balance(self): return self._balance getter and a matching @balance.setter def balance(self, value): ... that validates before setting self._balance. Because both the getter and setter are still accessed with the exact same account.balance / account.balance = value syntax as before, every single existing call site in the large program keeps working completely unchanged — nobody needs to go find-and-replace account.balance = x into account.set_balance(x) across the whole codebase. This is precisely why interviewers ask it: it tests whether a candidate understands that Python's property mechanism exists specifically to let an API's internal implementation evolve (adding real validation logic) without breaking its public interface, which is a genuinely valuable, real-world API design skill, not just trivia about a decorator's syntax.

Suggesting the fix requires renaming every external call site from account.balance = x to some new method call (defeating the entire point), or not recognizing this as a real, common software-evolution scenario rather than an artificial classroom exercise.

"After converting balance from a plain attribute to a @property with a validating setter, does old code written as account.balance = 500 (from before the change) need to be edited at all?" (No — that's the entire benefit; the assignment syntax is identical before and after the change, so every existing call site keeps working exactly as written, now silently gaining validation it didn't have before.)

9 If a class defines a @property getter for balance but never adds a matching @balance.setter, what happens if code tries account.balance = 500?

It raises an AttributeError, something like can't set attribute (the exact wording varies slightly by Python version). Defining only @property without a matching @x.setter creates a read-only property — the getter lets code read account.balance freely, but there is no defined behavior at all for assigning to it, so Python refuses the assignment outright rather than silently doing nothing or falling back to some default behavior. This is actually a deliberate, useful pattern in real class design: it's how a class exposes a genuinely computed or derived value — something that should never be set directly at all, only read — while still using clean attribute-style access syntax for reading it.

Assuming a property without a setter silently allows assignment anyway, or not recognizing "getter-only property" as an intentional, useful pattern for read-only computed values rather than an incomplete mistake.

"What's a realistic example of a value that should be a read-only @property with no setter at all?" (Something genuinely computed from other stored data rather than independently meaningful on its own — e.g. a full_name property computed by combining stored first_name and last_name attributes; setting full_name directly wouldn't make sense, since there'd be no clear way to split a new value back into the two underlying pieces.)

10 Why would a class use a @staticmethod instead of just writing a completely separate, ordinary function outside the class?

Functionally, very little differs — a @staticmethod genuinely behaves like an ordinary function with no automatic access to self or cls. The real reason to use one is organization and discoverability: if a piece of logic is conceptually tied to a specific class — like validating that a string is correctly formatted as that class's kind of ID or account number — grouping it inside the class as BankAccount.is_valid_account_number(s) keeps related code physically together and makes it obvious, to anyone reading the class, exactly which helper logic belongs to it. A loose function floating somewhere else in the file (or a different module entirely) doesn't carry that same clear association, and it's easy for a codebase to end up with a scattering of validation-style helper functions with no obvious home. The rule of thumb: if a helper function conceptually "belongs to" a class's domain but genuinely doesn't need any particular instance's data or the class itself to do its job, a @staticmethod is the right home for it.

Claiming a staticmethod has some special performance benefit or secretly different behavior compared to a plain function (it doesn't), or being unable to articulate the actual reason (organization/association with the class) beyond "it's just a style choice with zero justification."

"Inside a @staticmethod named is_valid_account_number, can the method reference self or cls at all?" (Not automatically — neither is passed in; the method only has access to whatever parameters it explicitly defines itself, exactly like a plain standalone function.)

11 Can a @classmethod call a @staticmethod defined in the same class, and vice versa?

Yes, both directions work, and it's a genuinely common pattern. A @classmethod automatically receives cls, so it can call a staticmethod defined in the same class as cls.is_valid_account_number(...) (or through a specific instance if one's available). A @staticmethod has no automatic cls or self, but if the class name is in scope (which it is, inside the class's own module), it can still call another staticmethod or classmethod by referring to the class directly, e.g. BankAccount.some_other_static(...) — it just can't reach any specific instance's data, since it was never given one. A realistic example: a @classmethod alternative constructor like from_string might call a @staticmethod validator like is_valid_account_number first, before actually building and returning the new instance, so invalid input is rejected before any object even gets constructed.

Claiming these two decorator types can't interact with each other at all, or not recognizing "classmethod validates input via a staticmethod before constructing" as a natural, common combination of the two.

"Inside @classmethod def from_string(cls, data): ..., what's a natural way to reuse a @staticmethod named is_valid_format defined in the same class, before actually constructing the new instance?" (Call it as cls.is_valid_format(data) — since cls refers to the class itself, this reaches the staticmethod the same way ClassName.is_valid_format(data) would, and the classmethod can check its result before deciding whether to proceed with return cls(...).)

12 What actually happens, step by step, when code runs account.balance where balance is a @property?

Even though account.balance looks like plain attribute access at the call site, @property secretly turns balance into what's called a descriptor at the class level, and Python's attribute lookup machinery checks for one before falling back to a plain instance attribute. Concretely: when account.balance is evaluated, Python sees that balance on the BankAccount class is a property object (not a plain value), so instead of returning some stored value directly, it calls the property's getter function — the method originally decorated with @property — passing account in as self, and returns whatever that method's body computes or returns. This is exactly why a property can compute a fresh value every single time it's read (like combining first_name and last_name into full_name on the fly) rather than needing a value to already sit in storage — every single account.balance read is a genuine function call happening behind attribute-access syntax, not a direct memory read.

Describing property access as "just reading a stored value directly," missing that it's actually invoking a getter method underneath every single time it's accessed.

"If a @property getter for balance is written as return self._balance * 1 (deliberately recomputed, not just returned directly), does every single account.balance read re-run that multiplication?" (Yes — a property getter is a real method invoked fresh on every single access; nothing about it is cached automatically unless the class deliberately adds caching logic itself.)

13 Is it possible to have a @property that's read-write for some code paths but effectively becomes "append-only" or restricted after some condition, like an account that's been closed?

Yes — and this is exactly the kind of real-world validation logic a @x.setter is built to handle, since the setter's body is ordinary Python code that can check whatever conditions actually matter, not just a fixed type/range check. A @balance.setter could check an internal flag like self._is_closed and raise an exception (say, a custom exception class from Chapter 13) if someone tries to change the balance on a closed account, in addition to its ordinary "reject negative values" validation. The call site still looks identical either way — account.balance = 500 — but the setter's internal logic can enforce arbitrarily rich business rules (closed-account checks, minimum-balance requirements, daily withdrawal limits) all in the one place every balance change is guaranteed to funnel through, rather than needing that logic duplicated at every spot in a program that might otherwise touch balance directly.

Believing a property setter can only do simple type or range checks, missing that it's a full method body capable of any validation logic, including checking other instance attributes or raising custom exceptions.

"If a @balance.setter raises a custom AccountClosedError when self._is_closed is True, and calling code doesn't wrap the assignment in a try/except, what happens when it tries closed_account.balance = 100?" (The program crashes with an unhandled AccountClosedError traceback, exactly like any other uncaught exception — the setter's validation logic ran, correctly rejected the assignment, and raising is how it communicates that rejection back up the call stack.)

14 In a real-world program, when would you reach for a plain instance attribute versus a full @property with a getter and setter?

A plain instance attribute is the right default for data that has no meaningful constraints and no computed logic attached — something like a name string that can genuinely be any value with no validation rule to enforce; wrapping every such attribute in a property "just in case" adds ceremony with no real payoff. A @property earns its keep specifically when at least one of these is true: the value needs validation before being stored (a balance that can't go negative, an age that can't be negative or absurdly large), the value is computed from other stored data rather than independently stored at all (a full_name derived from first_name/last_name), or the class needs the freedom to change its internal storage later without breaking any external code that already depends on attribute-style access. A reasonable real-world habit: start with a plain attribute when writing a class, and promote it to a property later specifically when a genuine need for validation or computed logic actually shows up — exactly the API-evolution scenario this chapter's questions cover, and precisely why @property exists in the first place rather than requiring every attribute to go through get_x()/set_x() from day one out of excessive caution.

Insisting every single attribute on every class should always be a @property "to be safe" (unnecessary ceremony for data with no real constraints), or never reaching for one even when a genuine validation or computed-value need clearly exists.

"A Person class has a plain nickname attribute with genuinely no constraints on what it can be set to. Does it need to be a @property?" (Not really — a plain instance attribute is perfectly fine there; a property is worth adding specifically once there's a real validation rule or computed-value need to enforce, not as a blanket default for every single attribute regardless of whether it needs one.)

Rapid-Fire Review

Quick recall check — fill in each blank and hit Check.

🎉 Perfect score — you're ready to talk about this chapter in an interview.
← Challenges Build the Project →