oop cheat sheet: classes, encapsulation, inheritance, polymorphism and abstraction, in python
Stacks · 12 min read · posted Nov 30, 2026, 9:10 pm
Most object-oriented programming (OOP) questions come back to the same five ideas: classes and objects, encapsulation, inheritance, polymorphism and abstraction. Once you can explain each one with a small example, the follow-up questions get a lot easier.
This is the cheat sheet from the reel. It covers the five things in it, in the same order. For each one you get when you reach for it, the syntax with a small example and what it prints, the mistake that usually bites, and something to practise on. After the five there's a section on how each one gets asked in interviews, with a short answer for each, and a note on composition over inheritance.
Every block here was run on Python 3.14.7, and the output under it is what it printed. Everything also runs on Python 3.10. Two error messages read differently on older versions, and both are pointed out where they come up.
the quick lookup
| i want to | write |
|---|---|
| a blueprint for objects | class Dog: |
| set up each new object | def __init__(self, name): |
| make an object | rex = Dog("Rex") |
| data that belongs to one object | self.name = name inside a method |
| data shared by every object | count = 0 in the class body |
a nice printout and == for free |
@dataclass on the class |
| mark something as internal | a leading underscore, self._balance |
| a read-only attribute | @property on a method |
| reuse another class | class Dog(Animal): |
| run the parent's version too | super().__init__(name) |
| check what something is | isinstance(rex, Animal) |
| see where Python looks for methods | Dog.__mro__ |
make len() or + work on your class |
def __len__(self):, def __add__(self, other): |
| say what every subclass must have | class Shape(ABC): with @abstractmethod |
the five in one line each
| idea | what it means |
|---|---|
| classes and objects | a class is the blueprint, an object is one thing built from it with its own data |
| encapsulation | an object's data is changed through its methods, so the object can keep itself valid |
| inheritance | a class can start from another class, reuse its methods, and replace the ones that differ |
| polymorphism | the same call does the right thing for each kind of object |
| abstraction | a base class says what has to exist, and leaves how it works to the subclasses |
1. classes and objects
When you reach for it. You have several things of the same kind, each with its own data and the same actions: users, bank accounts, shapes, cards in a deck. A class puts the data and the functions that work on it in one place.
The syntax. class makes the blueprint. Calling the class like a function makes an object and runs __init__ on it. self is the object the method was called on, so self.name = name stores the name on that one object.
class Dog:
def __init__(self, name):
self.name = name
self.toys = []
def give(self, toy):
self.toys.append(toy)
rex = Dog("Rex")
ivy = Dog("Ivy")
rex.give("ball")
print(rex.toys, ivy.toys)
print(rex.name, type(rex).__name__)
print(rex is ivy)
['ball'] []
Rex Dog
False
This is the one in the reel. Both dogs come from the same class, but each one got its own list in __init__, so giving Rex a ball leaves Ivy's list empty.
Second shape: a dataclass. When a class is mostly data, @dataclass writes __init__, a readable printout and == for you from the fields you list.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def dist(self):
return abs(self.x) + abs(self.y)
p = Point(3, 4)
print(p)
print(p == Point(3, 4))
print(p.dist())
Point(x=3, y=4)
True
7
Without @dataclass, print(p) shows something like <__main__.Point object at 0x...>, and == checks whether the two names point at the very same object, so two equal points would compare False.
What bites. Putting a list in the class body instead of in __init__. Anything written in the class body is one value on the class, shared by every object.
class Dog:
toys = []
def __init__(self, name):
self.name = name
def give(self, toy):
self.toys.append(toy)
rex = Dog("Rex")
ivy = Dog("Ivy")
rex.give("ball")
print(rex.toys, ivy.toys)
print(rex.toys is ivy.toys)
['ball'] ['ball']
True
A number or a string in the class body is fine as a shared default or a constant. It's lists, dicts and sets that bite, because every object appends to the same one. The other one is leaving self off a method's parameters: Python passes the object in anyway, and you get TypeError: Dog.give() takes 1 positional argument but 2 were given.
Practise.
- 1603. Design Parking System (Easy)
- 705. Design HashSet (Easy)
- 155. Min Stack (Medium)
2. encapsulation
When you reach for it. An object has rules its data has to follow: a balance can't go negative, a stack can't pop when it's empty, an email has to have an @ in it. If every change goes through a method, the method can check the rule, and no other code can break it by accident.
The syntax. Keep the data in an attribute that starts with an underscore, which tells other code it's internal, and give the object methods for every change you allow.
class Account:
def __init__(self):
self._balance = 0
def deposit(self, amt):
self._balance += amt
def withdraw(self, amt):
if amt > self._balance:
raise ValueError("not enough money")
self._balance -= amt
acct = Account()
acct.deposit(50)
acct.withdraw(20)
try:
acct.withdraw(100)
except ValueError as e:
print("refused:", e)
print(acct._balance)
refused: not enough money
30
This is the one in the reel (the reel raises a bare ValueError to keep the line short). The deposit and the first withdrawal go through, the third is refused, and the balance is still 30.
Second shape: a read-only property. Reading acct._balance from outside works, but it reaches past the methods. @property turns a method into something you read like an attribute, with no way to assign to it.
class Account:
def __init__(self):
self._balance = 0
@property
def balance(self):
return self._balance
def deposit(self, amt):
if amt <= 0:
raise ValueError("deposit must be positive")
self._balance += amt
acct = Account()
acct.deposit(50)
print(acct.balance)
try:
acct.balance = 1000
except AttributeError as e:
print(e)
50
property 'balance' of 'Account' object has no setter
On Python 3.10 that second line reads can't set attribute 'balance'. Either way, the only way to change the balance is deposit.
What bites. Thinking the underscore locks anything. Python has no private keyword. A single underscore is a convention that says "don't touch this from outside", and nothing stops code that ignores it. Two underscores make Python rename the attribute, which stops accidental clashes in subclasses, but it's still reachable under the new name.
class Account:
def __init__(self):
self._balance = 0
self.__pin = 1234
acct = Account()
acct._balance = -500
print(acct._balance)
try:
print(acct.__pin)
except AttributeError as e:
print(e)
print(acct._Account__pin)
-500
'Account' object has no attribute '__pin'
1234
So in Python encapsulation is a design habit more than a lock: the class offers methods, and everyone agrees to use them. In Java or C++, private is enforced by the compiler.
Practise.
- 2043. Simple Bank System (Medium)
- 1472. Design Browser History (Medium)
- Take the account above and add a
transfer(other, amt)method that refuses when the money isn't there and changes neither balance.
3. inheritance
When you reach for it. Two classes are the same kind of thing and share most of their code, and one is a more specific version of the other. A dog is an animal. A savings account is an account. If you can't say "is a" out loud and mean it, see composition below.
The syntax. Put the parent class in brackets after the name. The child gets every method the parent has. Writing a method with the same name in the child replaces, or overrides, the parent's one for that child.
class Animal:
def __init__(self, name):
self.name = name
def sleep(self):
return "Zzz"
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof!"
rex = Dog("Rex")
print(rex.name)
print(rex.sleep())
print(rex.speak())
print(isinstance(rex, Animal))
print([c.__name__ for c in Dog.__mro__])
Rex
Zzz
Woof!
True
['Dog', 'Animal', 'object']
This is the one in the reel. Dog has no __init__ and no sleep, so Python finds Animal's. Dog has its own speak, so that one wins. The last line is the method resolution order (MRO): the list of classes Python looks through, in order, when you call a method.
Second shape: extend the parent with super(). When the child needs everything the parent does plus a bit more, call the parent's version and then add to it.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def __repr__(self):
return f"Dog({self.name!r}, {self.breed!r})"
print(Dog("Rex", "collie"))
Dog('Rex', 'collie')
What bites. Writing an __init__ in the child and forgetting to call the parent's. The child's __init__ replaces the parent's completely, so whatever the parent set up never happens.
class Animal:
def __init__(self, name):
self.name = name
def intro(self):
return "I'm " + self.name
class Dog(Animal):
def __init__(self, name, breed):
self.breed = breed
rex = Dog("Rex", "collie")
try:
print(rex.intro())
except AttributeError as e:
print(e)
'Dog' object has no attribute 'name'
The error only shows up when something reads name, which can be a long way from the real mistake. The other one is deep chains, five classes tall, where finding out what a method does means reading all five. Two levels is plenty most of the time.
Practise.
- Write
Shapewith adescribe()method that returns"a shape", andSquare(Shape)that overrides it. Then haveSquare.describecallsuper().describe()and add to it. - Give
Animalan__init__that takes a name andDogone that takes a name and a breed. PrintDog.__mro__and say what Python checks, in order, forrex.sleep().
4. polymorphism
When you reach for it. You have a collection of different kinds of things and you want to do the same job to each one without checking what kind it is. Drawing every shape on a screen, paying every kind of employee, saving every kind of document.
The syntax. Give each class a method with the same name. The calling code just calls it, and each object runs its own version.
class Square:
def __init__(self, n):
self.n = n
def area(self):
return self.n ** 2
class Rect:
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h
shapes = [Square(3), Rect(5, 2), Square(2)]
for shape in shapes:
print(type(shape).__name__, shape.area())
Square 9
Rect 10
Square 4
This is the one in the reel. The loop never asks what each shape is. shape.area() runs Square's code for the squares and Rect's code for the rectangle.
Square and Rect don't share a parent here. Python only cares that the method exists when it's called, which is called duck typing: if it has an area(), it can go in the list. In Java the same loop needs a shared parent class or interface, which is section 5.
Second shape: your class with Python's own operators. len(), + and print are polymorphic too. They call special methods, and your class can supply them.
class Playlist:
def __init__(self, songs):
self.songs = songs
def __len__(self):
return len(self.songs)
def __add__(self, other):
return Playlist(self.songs + other.songs)
def __repr__(self):
return f"Playlist({self.songs})"
a = Playlist(["intro", "verse"])
b = Playlist(["outro"])
print(len("hello"), len([1, 2]), len(a))
print(a + b)
print(1 + 2, "ab" + "cd")
5 2 2
Playlist(['intro', 'verse', 'outro'])
3 abcd
What bites. Checking the type yourself. A chain of isinstance checks has to be edited every time a new kind of shape turns up, and the one you forget falls through quietly.
class Square:
def __init__(self, n):
self.n = n
class Rect:
def __init__(self, w, h):
self.w, self.h = w, h
class Circle:
def __init__(self, r):
self.r = r
def area(shape):
if isinstance(shape, Square):
return shape.n ** 2
if isinstance(shape, Rect):
return shape.w * shape.h
print(area(Square(3)), area(Circle(1)))
9 None
With an area() method on each class, a new shape brings its own area along and nothing else changes. The other one is a typo in one class's method name, like def aera(self). Python only finds out when the loop reaches that object, as an AttributeError. Section 5 is how you catch that earlier.
Practise.
- Add a
Circlewitharea()usingmath.pito the loop above, without touching the loop. - Give
Rectan__eq__soRect(2, 3) == Rect(2, 3)isTrue, then check whatRect(2, 3) == Rect(3, 2)should be and why.
5. abstraction
When you reach for it. You're writing the base class that other classes will fill in, and you want to say up front what every one of them has to provide. A payment provider must have charge(). A shape must have area(). The code that uses them only needs to know those names, not how each one works.
The syntax. Inherit from ABC and mark the required methods with @abstractmethod. Python then refuses to make an object of any class that still has one of them missing.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, n):
self.n = n
def area(self):
return self.n ** 2
print(Square(3).area())
try:
Shape()
except TypeError as e:
print(e)
9
Can't instantiate abstract class Shape without an implementation for abstract method 'area'
This is the one in the reel. Square fills in area(), so it can be made and used. Shape itself can't be made at all. On Python 3.11 and older the message reads Can't instantiate abstract class Shape with abstract method area instead.
Second shape: a subclass that forgets, and shared code in the base. The base class can also hold normal methods that rely on the abstract one. A subclass that misses the abstract method fails when you make it, not later when something calls it.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
def describe(self):
return f"{type(self).__name__} with area {self.area()}"
class Square(Shape):
def __init__(self, n):
self.n = n
def area(self):
return self.n ** 2
class Circle(Shape):
def __init__(self, r):
self.r = r
def aera(self):
return 3.14159 * self.r ** 2
print(Square(2).describe())
try:
Circle(1)
except TypeError as e:
print(e)
Square with area 4
Can't instantiate abstract class Circle without an implementation for abstract method 'area'
That's the typo from section 4, caught the moment a Circle is made.
What bites. Forgetting (ABC). @abstractmethod only does anything on a class that inherits from ABC. Without it the decorator is ignored and the "abstract" class makes objects happily.
from abc import abstractmethod
class Shape:
@abstractmethod
def area(self):
pass
s = Shape()
print(s.area())
None
The other one is making everything abstract. If there's only ever going to be one subclass, the base class is extra code to read for no gain. Add the abstraction when the second kind turns up.
Practise.
- Write an abstract
Notifierwithsend(msg), andEmailNotifierandSmsNotifierthat return different strings. Loop over a list of both. - Make a subclass that forgets
sendand read the error you get when you create it.
how each one gets asked
Most OOP questions are "explain X" or "X vs Y". Say the short answer, then give the small example from the section above.
"What's the difference between a class and an object?" A class is the blueprint: it says what data and methods its objects have. An object is one instance made from it, with its own copy of that data.
"Explain encapsulation. How does Python make things private?" Encapsulation means an object's data is changed through its methods, so the object can check every change and stay valid. Python doesn't enforce privacy: a single underscore is a convention, and a double underscore renames the attribute but doesn't hide it.
"Overriding vs overloading?" Overriding is a subclass replacing a method it inherited, keeping the same name, so the subclass's version runs for its objects. Overloading is several methods with the same name and different parameters in one class, which Java has and Python doesn't, so in Python you use default arguments instead.
"Explain polymorphism." The same call runs different code depending on the object it's called on, like shape.area() in a loop over different shapes. It lets the calling code stay the same when a new kind of object is added.
"Abstraction vs encapsulation?" Abstraction decides what the outside world sees: a shape has area(), and the caller doesn't care how it's worked out. Encapsulation protects how it's done inside: the data stays behind methods, so nobody can put the object into a bad state.
"Abstract class vs interface?" In Java an interface is mostly a list of methods a class promises to have, with no instance fields, and a class can implement many of them, while an abstract class can hold fields and shared code but a class can only extend one. Python has no separate interface keyword, so an ABC with only abstract methods plays the interface role, and Python allows inheriting from several classes.
"Inheritance vs composition?" Inheritance is "is a": a Dog is an Animal and gets its methods. Composition is "has a": a Car has an Engine and calls it, which is usually easier to change later, as the next section shows.
composition over inheritance
Inheritance ties the child to the parent for good. If a Car inherits from PetrolEngine, an electric car needs a new class, and a car with both needs something worse. Composition gives the car an engine object instead, and the car calls it.
class PetrolEngine:
def start(self):
return "vroom"
class ElectricEngine:
def start(self):
return "hum"
class Car:
def __init__(self, engine):
self.engine = engine
def start(self):
return "car: " + self.engine.start()
car = Car(PetrolEngine())
print(car.start())
car.engine = ElectricEngine()
print(car.start())
car: vroom
car: hum
Car never changes, and the engine can be swapped while the program runs. It's also polymorphism at work: Car calls start() without caring which engine it has.
The rule of thumb: inherit when the child really is a special case of the parent and will stay one, and use composition when you're only after some of another class's behaviour. When you're not sure, composition is the easier one to undo.
how to practise with this
One section at a time. Type the reel's example out, run it, then change one thing and predict the output before you run it again. Most of what sticks comes from the predictions you get wrong.
For the "explain X" questions, say the two-sentence answer out loud, then write the smallest example that shows it. An interviewer usually asks for the example next.
honest limitations
These five are the core, not all of OOP. SOLID, design patterns like factory and observer, and class design questions such as "design a parking lot" build on them and aren't covered here.
Everything here is Python, and Python is relaxed about OOP compared with Java or C++. It has no private, no interfaces, no method overloading, and it allows inheriting from several classes. If the interview is in Java, learn private, interface and extends as well. The ideas carry over even where the keywords don't.
The LeetCode problems above are design problems where you write a class, which is the closest LeetCode gets to OOP. The other practice items are short exercises to do on your own.
If you're preparing for the coding rounds too, the python cheat sheet covers the syntax, and the coding interview cheat sheet and the data structures cheat sheet cover the problems.