Classes & OOP
What Are Classes?
A class is like a cookie cutter. The cookie cutter itself isn't a cookie — it's a template for making cookies. Each cookie you stamp out is an object (also called an instance). Every cookie has the same shape, but you can decorate them differently (different attributes).
In programming terms:
- Class = the blueprint (defines what data and behaviors something has)
- Object/Instance = a specific thing made from that blueprint
- Attributes = data stored on the object (like
name,age), often using types like lists and dictionaries - Methods = functions that belong to the object (like
speak(),jump())
Your First Class
The self Parameter
Every method in a class takes self as its first parameter. Think of self as a mirror — it lets the object refer to itself. When you call buddy.bark(), Python secretly passes buddy as self, so the method knows which dog is barking.
The __init__ method is the constructor — it runs automatically when you create a new object. It's where you set up the object's starting state.
Special (Dunder) Methods
Python has special methods surrounded by double underscores ("dunder" methods) that let your objects work with built-in operations like print(), len(), +, and comparisons.
__str__— Whatprint()andstr()use. Make your object human-readable.__repr__— The "developer" view. Should ideally show how to recreate the object.__len__— Makeslen(obj)work.__eq__— Defines what==means for your objects.
Dunder Methods in Action
Inheritance — Building on What Exists
Inheritance lets you create a new class based on an existing one. The new class (child) gets all the attributes and methods of the existing class (parent), and can add or override them.
Think of it like a family business: the child inherits the parent's recipes (methods) and ingredients (attributes), but can also develop their own specialties.
Inheritance & super()
super().__init__() in the child class. Without it, the parent's setup code never runs, and your object will be missing attributes. Always call super() first in your child's __init__!