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.
1. Defining the Blueprint
Section titled “1. Defining the Blueprint”We use the class keyword. By convention, class names use PascalCase.
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}.")2. Under the Hood: __new__ vs __init__
Section titled “2. Under the Hood: __new__ vs __init__”Most beginners think __init__ creates the object. It does not.
__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.__init__: This is the initializer. It receives the object already created by__new__and populates it with data.
- You call
r = Robot("T-800", 101). - Python calls
Robot.__new__to allocate memory. - Python calls
Robot.__init__(r, "T-800", 101)to set the attributes.
3. The self Mystery
Section titled “3. The self Mystery”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.
4. The Class Namespace
Section titled “4. The Class Namespace”Every class and every instance has its own Namespace (stored in a dictionary called __dict__).
r = Robot("T-800", 101)
# Inspect the instance's dataprint(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.
5. Summary Table
Section titled “5. Summary Table”| Component | Role |
|---|---|
class | Defines the blueprint and shared behavior. |
self | A reference to the current instance. |
__init__ | Sets up the initial state (data) of an object. |
| Instance | A concrete object living in memory. |
__dict__ | The underlying dictionary where attributes are stored. |