Skip to content

Class Anatomy & The Lifecycle of an Object

In Python, a Class is a blueprint, and an Object is the house built from that blueprint. However, beneath this simple analogy lies a sophisticated mechanism of memory allocation and attribute binding.

To master Object-Oriented Programming (OOP), you must understand not just how to define a class, but how Python brings an instance to life.


We use the class keyword. By convention, class names use PascalCase.

robot.py
class Robot:
"""A simple class representing a robotic entity."""
def __init__(self, model, serial_number):
self.model = model
self.serial_number = serial_number
def greet(self):
print(f"Hello, I am {self.model}. My ID is {self.serial_number}.")

Most beginners think __init__ creates the object. It does not.

  1. __new__: This is the actual constructor. It creates the object in memory and returns it. You rarely need to override this unless you are working with immutable types or metaclasses.
  2. __init__: This is the initializer. It receives the object already created by __new__ and populates it with data.
  1. You call r = Robot("T-800", 101).
  2. Python calls Robot.__new__ to allocate memory.
  3. Python calls Robot.__init__(r, "T-800", 101) to set the attributes.

Why do we have to put self in every method?

Python does not have a hidden this pointer like C++ or Java. Instead, it follows the principle: “Explicit is better than implicit.”

When you call my_robot.greet(), Python automatically converts it into: Robot.greet(my_robot)

The self parameter is just a variable that receives the reference to the specific instance you are working with. You could name it this or me, but using self is a non-negotiable community standard.


Every class and every instance has its own Namespace (stored in a dictionary called __dict__).

namespace_check.py
r = Robot("T-800", 101)
# Inspect the instance's data
print(r.__dict__)
# Output: {'model': 'T-800', 'serial_number': 101}

When you look for an attribute (like r.model), Python first looks in the Instance __dict__. If it’s not there, it looks in the Class __dict__. This hierarchy is the foundation of inheritance.


ComponentRole
classDefines the blueprint and shared behavior.
selfA reference to the current instance.
__init__Sets up the initial state (data) of an object.
InstanceA concrete object living in memory.
__dict__The underlying dictionary where attributes are stored.