Interview Questions: OOP Basics
Object-oriented programming is where interviewers start separating "can write a script" from "can design software that grows." This set covers what a class actually is versus an object/instance, why self has to be the first parameter of every instance method, how __init__ compares to other languages' "constructor," class attributes vs. instance attributes and the classic mutable-class-attribute bug, __str__ vs. __repr__, why bundling data and behavior into a class beats a pile of separate dicts and functions, and encapsulation as a concept even before Chapter 15's deeper access-control tools.
1 What's the actual difference between a class and an object?
A class is a blueprint — it defines what attributes and methods every object built from it will have, but it isn't itself a usable "thing" holding real data. An object (also called an instance) is one concrete thing actually built from that blueprint, with its own real values stored in its own attributes. class Dog: describes that every dog has a name and can bark; rex = Dog("Rex") is one specific dog that actually exists in memory, with rex.name holding the real string "Rex". The same class can produce many different objects — rex and fido = Dog("Fido") both come from the exact same Dog blueprint, but they're two separate objects with independent data, exactly like a cookie cutter (the class) versus the actual cookies it stamps out (the objects), where each cookie can still get its own individual decoration.
Using "class" and "object" interchangeably, or saying a class "stores" a program's actual data — the class only defines the shape; each object holds its own independent values.
Follow-up"If class Dog: is defined once, and a program creates rex = Dog("Rex") and fido = Dog("Fido"), how many Dog classes exist, and how many Dog objects exist?" (One class — the blueprint is defined a single time — and two objects, rex and fido, each an independent instance built from that one blueprint with its own separate data.)
2 Why does every instance method need self as its first parameter, and what happens if you forget it?
self is how an instance method knows which specific object it's currently operating on — without it, a method would have no way to tell whether it was called on rex or fido, since the method's code is shared by every instance of the class. When Python evaluates rex.bark(), it automatically rewrites that call behind the scenes into Dog.bark(rex) — the object the method was called on gets passed in as the first argument, and by convention that first parameter is named self so the method body can read self.name and get this specific dog's name rather than some other dog's. Leaving self off a method definition doesn't make the method "not need an object" — Python still passes the calling object in automatically, so the method ends up receiving one more positional argument than its parameter list accounts for, and calling it raises a TypeError about a mismatched argument count.
Believing self is just boilerplate Python requires for no real reason, or not knowing that obj.method(args) is automatically translated into Class.method(obj, args) under the hood.
"A method is defined as def bark(): return "Woof" (no self parameter at all) inside class Dog:, and code calls rex.bark(). What happens?" (A TypeError is raised — Python still automatically passes rex in as an argument to bark, but the method was defined to take zero parameters, so it receives one argument it has no parameter to catch, e.g. bark() takes 0 positional arguments but 1 was given.)
3 Is __init__ the same thing as a "constructor" in languages like Java or C++?
Close, but not identical — and the distinction is worth knowing precisely. In Python, the object itself is actually created by a separate, rarely-touched method called __new__; by the time __init__ runs, the object already exists in memory as a blank instance, and __init__'s real job is initializing that already-created object's attributes with starting values — hence the name. In languages like Java or C++, "the constructor" typically both allocates the object's memory and sets its initial state in one combined step. In everyday Python usage the difference rarely matters in practice — __init__ is where you set up an object's starting attributes, full stop — but a careful answer distinguishes "the method that creates the object" (__new__, almost never overridden in ordinary code) from "the method that initializes its attributes" (__init__, used in essentially every class).
Insisting __init__ "creates the object" with no awareness that object creation and attribute initialization are technically two separate steps in Python (even though only the second one is something you'll typically write).
"If a class defines __init__ but never touches __new__ at all, does the object still get created successfully?" (Yes — __new__ has a default implementation inherited automatically that handles actually creating the blank object, so a class only needs to define __init__ to set up that object's attributes; overriding __new__ itself is rare and outside what this course covers.)
4 What's the difference between an instance attribute and a class attribute?
An instance attribute is set inside __init__ (or another instance method) as self.something = value, and every object gets its own separate copy — changing rex.name has zero effect on fido.name. A class attribute is defined directly inside the class body, outside any method, and is shared by every instance of that class — there's only one copy of it in memory, and every object looks up the same shared value unless that specific instance later gets its own instance attribute of the same name. Class attributes are the right tool for data that's genuinely the same across every instance (a species name shared by every Dog, a fixed interest rate shared by every Account), while instance attributes are for data that's meant to differ from object to object (each dog's own name, each account's own balance).
Not knowing that a class attribute is shared across every instance rather than copied per-instance, or defining data that should clearly vary per-object (like a name or balance) as a class attribute instead of an instance attribute.
Follow-up"If Dog has a class attribute species = "Canis familiaris", and no instance ever sets its own species, how many copies of that string exist in memory across 100 Dog objects?" (One — every one of the 100 objects looks up the same single shared class attribute; no per-instance copy is made unless an instance is individually given its own species attribute that would then shadow the class-level one for that object only.)
5 A class defines a mutable class attribute like items = [] instead of setting it in __init__. What goes wrong, and why is this such a common real interview question?
Because a class attribute is shared by every instance, a mutable one like a list or dict becomes one single shared object that every instance secretly points to — there aren't separate lists per object, just one list every object can see and mutate. So cart_a.items.append("apple") doesn't just affect cart_a; it mutates the one shared list, which means cart_b.items (a completely different, supposedly-empty cart) suddenly shows ["apple"] too, even though nothing was ever explicitly added to cart_b. This is a genuinely common real-world bug, not just a trivia question, because the code looks completely reasonable at a glance — it only breaks once a program actually creates more than one instance and starts mutating that attribute, which can slip through code review and testing if only one instance was ever exercised. The fix is to initialize mutable data inside __init__ as an instance attribute instead — self.items = [] — so every object gets its own separate, freshly created list rather than sharing one.
Not immediately recognizing items = [] written directly in a class body (rather than in __init__ as self.items = []) as a bug waiting to happen, or being unable to explain why it happens (shared mutable state) rather than just knowing "it's wrong."
"Given class Cart: with items = [] as a class attribute (not in __init__), if code creates cart_a = Cart() and cart_b = Cart(), then calls cart_a.items.append("apple"), what does cart_b.items show?" (["apple"] — both instances share the exact same list object in memory, so appending through cart_a is visible through cart_b too, even though cart_b never had anything explicitly added to it.)
6 What's the fix for the mutable-class-attribute bug, and why does it work?
Move the mutable value's creation into __init__ as an instance attribute: self.items = [] instead of items = [] directly in the class body. Because __init__ runs separately every single time a new object is created, self.items = [] builds a brand-new, independent empty list for each object — there's no longer one shared list that every instance points to, just one distinct list per instance. The general rule this generalizes to: any default value that's mutable (a list, dict, or set) should be created fresh inside __init__, never written directly as a class-level attribute, specifically because a class-level mutable value is created exactly once, at class-definition time, and shared forever after by every instance that doesn't override it.
Suggesting the fix is to just "reset the list at the start of each method" rather than understanding the actual root cause (one shared list object) that self.items = [] in __init__ permanently eliminates.
"After changing items = [] (class attribute) to self.items = [] inside __init__, does cart_a.items.append("apple") still affect cart_b.items?" (No — each call to Cart() now runs __init__ separately and creates its own new empty list, so cart_a and cart_b hold two completely independent lists and mutating one has no effect on the other.)
7 What's the difference between __str__ and __repr__, and when does Python use each one?
__str__ defines an object's readable, human-facing string form — it's what runs when code calls print(obj) or str(obj), and it should read naturally, like "Point(1, 2)" or "Rex, a 3-year-old dog". __repr__ defines an object's unambiguous, developer-facing string form, meant for debugging, logging, and interactive-shell output — the convention is that it should ideally look like valid Python code that could recreate the object (e.g. "Point(x=1, y=2)"). Python falls back to __repr__ in a few specific situations where __str__ isn't defined or isn't the one being asked for: printing an object inside a list or dict always uses each element's __repr__ (never __str__), and typing a bare object's name in an interactive session displays its __repr__. If a class defines __repr__ but not __str__, print() falls back to using __repr__ too, since Python needs some readable string when neither is explicitly the perfect fit and __repr__ is the safer universal fallback.
Treating __str__ and __repr__ as interchangeable with no distinction, or not knowing that printing objects inside a list/dict uses __repr__ for each element rather than __str__.
"A class defines both __str__ (returning "Point(1, 2)") and __repr__ (returning "Point(x=1, y=2)"). What does print([Point(1, 2)]) actually output?" ([Point(x=1, y=2)] — printing a list calls repr() on each of its elements individually, not str(), so the __repr__ form is what shows up even though this is technically a print() call.)
8 What happens if a class defines neither __str__ nor __repr__, and why is that a problem worth fixing?
Every class automatically inherits a default __repr__ (used as a fallback by print() too, when __str__ is also missing) that produces something like <__main__.Dog object at 0x7f2b3c1a4d90> — the class name and the object's raw memory address, which tells a developer essentially nothing useful about that specific object's actual data. That's a real, common beginner trap: printing a list of custom objects to "check the data looks right" instead shows a wall of meaningless memory-address strings, making debugging much harder than it needs to be. Defining __str__ (and ideally __repr__ too) is a small amount of code that turns every print(obj), every debug log, and every element shown inside a list or dict into something a human can actually read and reason about, instead of an opaque object reference.
Not recognizing the default <__main__.ClassName object at 0x...> output as exactly what happens when neither dunder method is defined, or treating that default output as somehow acceptable for anything beyond the very earliest throwaway debugging.
"A class defines no __str__ and no __repr__ at all. What does print(some_instance) show?" (Something like <__main__.ClassName object at 0x7f...> — the default representation showing the class name and the object's memory address, with none of that specific object's actual attribute values visible.)
9 Why is bundling related data and behavior into a class better than a pile of separate dicts and standalone functions, once a program grows?
A dict-and-functions approach requires every function to take the dict as a parameter and trust that the caller passes one shaped correctly — nothing actually enforces that a "book" dict has a "title" key, or that checkout_book(book_dict) is only ever called with something that's genuinely meant to represent a book; a typo'd key or a dict from the wrong part of the program fails at runtime, often far from where the mistake actually happened. A class fixes this by bundling the data's shape and the operations that make sense on it in one place: __init__ guarantees every Book object actually has a title, author, and is_checked_out the moment it's created, and a method like book.check_out() reads far more clearly at the call site than a free-floating check_out_book(some_dict) that gives no hint what kind of dict is expected. As a program grows to have many related pieces of data and behavior, this bundling keeps related code physically together and self-documenting instead of scattered across separate functions that all silently assume a specific dict shape.
Treating "use a class" as a stylistic preference with no concrete justification, rather than being able to name the specific risk (no guaranteed shape, behavior scattered away from its data) that dicts-and-functions carries as a program grows.
Follow-up"A dict-based version has a function checkout_book(book) that assumes every dict passed in has an "is_checked_out" key. What happens if it's called with a dict that's missing that key?" (A KeyError at runtime, from wherever inside checkout_book first tries to read book["is_checked_out"] — nothing earlier in the program stopped a malformed dict from being created or passed in, whereas a Book class's __init__ would have guaranteed that attribute existed on every single object from the moment it was constructed.)
10 What does "encapsulation" mean, even before Chapter 15's deeper access-control tools?
At its core, encapsulation means keeping an object's data and the logic that operates on that data bundled together inside one class, rather than scattering related pieces of logic across a program with no clear owner. Even without Chapter 15's later tools for actually restricting attribute access, a class already achieves a meaningful first layer of this just by design: instead of a loose balance variable that any part of a program could accidentally set to a nonsensical value, an Account class can expose a deposit(amount) method that's the one sanctioned way to change self.balance, making it far more obvious where balance changes are supposed to happen and easier to add a rule (like rejecting a negative deposit) in exactly one place. It's a conceptual habit at this stage — "let the class own its data and provide clear methods for interacting with it" — well before Chapter 15 introduces properties and naming conventions that actually enforce restricted access.
Confusing encapsulation with strict access control that Python doesn't fully enforce yet at this stage, or failing to identify the simpler, real benefit already available now: grouping data with the specific methods meant to change it, instead of leaving that data changeable from anywhere with no clear, obvious entry point.
Follow-up"Without any of Chapter 15's tools yet, what's one concrete way a BankAccount class already practices encapsulation just by having a deposit(amount) method instead of code setting account.balance += amount directly from anywhere in a program?" (Every deposit funnels through one method, so a rule like "reject negative or zero deposit amounts" can be enforced in exactly one place inside deposit(), instead of needing to be repeated — or accidentally forgotten — everywhere in the program that happens to touch balance directly.)
11 Can two different instances of the same class have completely different sets of instance attributes?
In ordinary, correctly written Python, no — if every instance is created through the same __init__, every instance ends up with the same set of instance attributes, since __init__'s body runs identically for each one, just with different argument values. But Python doesn't technically forbid it: nothing stops code outside __init__ from later doing rex.favorite_toy = "ball" on just one specific Dog object, which gives that one instance an attribute no other Dog has. This is legal but generally a code smell in real programs — if every instance of a class is supposed to have some particular piece of data, it belongs in __init__ so every object gets it consistently and predictably, rather than relying on attributes being bolted onto specific instances ad hoc after the fact.
Claiming Python enforces that every instance must have identical attributes (it doesn't — attributes can technically be added to one specific instance after creation), or, in the other direction, treating that flexibility as a good general practice rather than recognizing it as something to generally avoid in favor of setting all expected attributes in __init__.
"If rex = Dog("Rex") and code later runs rex.favorite_toy = "ball", does fido = Dog("Fido") (created from the same class) also get a favorite_toy attribute?" (No — that assignment only touches rex, the one specific object it was run on; fido has no favorite_toy attribute at all unless the exact same assignment is separately made on fido too.)
12 Why can a class attribute be read through an instance (rex.species) even though it's never set inside __init__?
When Python looks up rex.species, it first checks whether rex itself (the specific instance) has an attribute named species set directly on it. If it doesn't — which is the case whenever species was only ever defined at the class level and never assigned as self.species = ... inside __init__ — Python's attribute lookup then falls back to checking the class the instance belongs to, finds it defined there, and returns that shared value instead. This fallback is exactly why a class attribute appears accessible "through" any instance without each instance needing its own copy: instance lookup checks the instance first, then falls back to the class, and a class attribute only lives at that second, shared level unless some later code deliberately gives one specific instance its own copy of the same name.
Believing class attributes are somehow automatically copied onto every instance at creation time (they aren't — there's exactly one shared copy, and instance lookup falls back to find it only when the instance itself has no attribute of that name).
Follow-up"If code runs rex.species = "Wolf" (assigning directly on the instance, not changing the class), does fido.species (a different Dog instance) change too?" (No — that assignment creates a brand-new instance attribute on rex specifically, which now shadows the class attribute for rex only; fido has no instance-level species of its own, so its lookup still falls back to the original shared class attribute, unchanged.)
13 In a real-world program, how would you decide whether something should be its own class versus just a dict or a handful of loose variables?
The signal to reach for a class is when a piece of data has both a consistent shape (the same set of related fields, every time) and behavior that naturally belongs with it (operations that only make sense in the context of that specific data). A single one-off piece of data used in exactly one place, with no real operations attached to it, is often fine as a plain variable or a small dict — introducing a class for it would be unnecessary ceremony. But something like a book in a library system, a student in a grade tracker, or a task in a to-do app has a genuinely fixed shape (a book always has a title, author, and checked-out status) and clear associated behavior (checking a book out, marking a task done) that keeps showing up together across a growing program — that combination of "recurring shape" plus "recurring behavior" is exactly the signal that a class will keep the code more organized than a dict passed between a dozen separate functions.
Red flagsReaching for a class for absolutely everything regardless of whether the data has any real associated behavior (over-engineering), or, in the other direction, insisting dicts and loose functions are "simpler" even once a program clearly has recurring, structured data with behavior that keeps needing to operate on it.
Follow-up"A program tracks a single one-off configuration value used in exactly one place with no associated behavior. Does that need its own class?" (Not really — a single plain variable or a small dict is perfectly reasonable there; a class earns its keep once there's a recurring, consistently shaped piece of data with real behavior attached to it, not for a single isolated value used nowhere else.)
14 If a class's __init__ takes parameters with default values, like def __init__(self, title, is_checked_out=False):, what's the actual reason for giving is_checked_out a default instead of always requiring it?
A default value lets the vast majority of realistic calls stay simple — a newly added book is checked-out status False in essentially every real case, so requiring every single caller to explicitly type Book("Title", "Author", "1234", False) just to state the overwhelmingly common case adds noise with no real benefit. Giving is_checked_out=False a default means the ordinary call, Book("Title", "Author", "1234"), already does the right thing, while a caller with a genuinely unusual need (constructing a Book object that represents one already checked out, say when loading saved data) can still override it explicitly with Book("Title", "Author", "1234", is_checked_out=True). This is the exact same "give the common case a sensible default, let the uncommon case override it" logic Chapter 7 introduced for ordinary function parameters — it applies identically inside __init__, since __init__ is just a regular method with regular parameters.
Not connecting default parameter values inside __init__ back to the same default-argument rules already taught for ordinary functions, or making every single __init__ parameter mandatory even when one has an obvious, overwhelmingly common default value.
"With def __init__(self, title, is_checked_out=False):, does calling Book("Dune") raise an error, and what does is_checked_out end up being for that object?" (No error — is_checked_out simply takes on its default value of False since the caller didn't supply one, exactly like any other Python function with a default parameter value.)
Rapid-Fire Review
Quick recall check — fill in each blank and hit Check.