Classes, Instances & the self Parameter
Understand Python object-oriented model: classes as blueprints, instance memory allocation, the explicit self parameter, instance dictionaries, and avoiding method signature errors.
Classes as Blueprints and Concrete Instances
In Python, a class is a blueprint for creating objects. You define a class using the class keyword followed by the class name in CamelCase and a colon.
An instance is a concrete realization of that class allocated in heap memory. When you call car = Car('electric'), Python creates a new object and invokes the class initializer __init__ to configure its state.
Every instance maintains its own separate dictionary of attributes in instance.__dict__. Changes made to one instance do not affect other instances of the same class.
The Explicit self Parameter
Unlike languages such as Java or C++ where the current instance is referenced implicitly via this, Python makes the instance reference completely explicit. By convention, the first parameter of any instance method is named self.
When you invoke a method on an instance using dot syntax car.drive(60), Python translates this behind the scenes into Car.drive(car, 60).
Because Python passes the instance as the first argument automatically, omitting self in the method signature causes runtime parameter count mismatches.
Instance Attributes vs Class Attributes
Instance attributes are assigned to self inside __init__ (e.g. self.speed = 0). Each instance owns an independent copy.
Class attributes are defined directly inside the class body outside any method. They are attached to the class object itself and are shared by all instances.
Class attributes are ideal for constants or tracking shared counts (for example, species = 'Canis lupus'). Be cautious with mutable class attributes like lists, as modifying them affects all instances simultaneously.
The Class Blueprint & Instance Stamping Studio
Stamp out fresh instance objects from a class blueprint into heap memory. Observe how calling an instance method automatically binds and passes the instance reference pointer into the self parameter.
dog1.bark(), Python translates it behind the scenes to Dog.bark(dog1). The instance pointer is explicitly passed into the self parameter.Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- A class is a blueprint; an instance is an allocated object in heap memory with its own __dict__.
- The first parameter of any instance method must be self, representing the specific instance being operated on.
- Calling obj.method(arg) is syntactic sugar for Class.method(obj, arg).
- Instance attributes belong to self; class attributes are shared across all instances on the class object.
- __init__ initializes object state and must always return None.
Done with this concept?
Mark it complete to track your progress. No login needed.