InterviewPrepKit

Home / Cheat Sheet / Algorithms & Data Structures with Python

Cheat sheet

Classes and Objects

Read the full lesson →

A class bundles data and behavior into your own kind of thing; an object is one concrete instance built from it.

Core terms

  • Class: the blueprint (written once). Object / instance: a concrete thing built from it (many).
  • Attribute: data stored on an object, read as obj.x. Each object has its own.
  • Method: a function defined inside a class; takes self first.
  • p is q is False for two separate objects even if built the same way.

__init__ and self

  • __init__ runs at construction to set starting data.
  • self is the object being worked on; Python passes it automatically. You never pass it yourself.
  • self.x = x stores value x onto this object. Set per-object data here.
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def distance_to_origin(self):
        return (self.x**2 + self.y**2) ** 0.5

Dunder methods

  • Dunder (double-underscore) methods run on built-in syntax:
    • __init__ — construction.
    • __repr__ — printing; must return a string, ideally one that recreates the object.
    • __len__ — makes len(obj) work.
    • __eq__ — defines ==; without it, == compares identity (memory), not contents.

Encapsulation

  • Encapsulation: keep internal data private, interact only through methods.
  • Leading underscore (self._items) means “internal, do not touch from outside.” Convention only, not enforced.
  • Public methods can stay stable while internals change.

Class vs dict

  • dict: plain data, no behavior; keys not fixed or decided at runtime; a quick bag of values.
  • class: data has behavior (methods); fixed reusable shape; want __repr__, __eq__, or encapsulation; many instances.
  • Functions that all take the same dict first argument want to be a class.

Pitfalls

  • Forgetting self — use self.x, not bare x, or you get a local variable.
  • Method without ()p.method is the function object; p.method() calls it.
  • Mutable value in the class body (e.g. items = [] outside a method) is shared by every instance; initialize in __init__.
  • == compares identity until you define __eq__.
  • pop/peek on an empty container raises; check is_empty() first.
Want the full picture? The lesson has the derivations, worked examples, and diagrams this card compresses into bullets. Read the full lesson →
Report a bug