Advertisement
When you create something new in code, it usually needs some initial setup, like giving a name to a user profile or setting the level of a new game character. In Python, this kind of prep work is handled by a special method called __init__. It's part of how Python classes work, but its name and double underscores often make it feel confusing to beginners.
The purpose of __init__ is simple: it lets you define what should happen when a new object is made. If you’ve worked with classes in Python, you’ve probably seen it already. This guide explains how __init__ fits into object creation, how it stores information, and how you can customize it to suit different needs.
The __init__ method is a part of every Python class. It's what Python uses to prepare an object right after it’s created. Think of it like a setup function that automatically runs when you build something from a class.
It always starts with two underscores before and after: __init__. These signals tell Python that this method plays a specific role—it’s not just a regular function you call on your own.
Here’s a small class to show how it works:
python
CopyEdit
class Animal:
def __init__(self, species):
self.species = species
When you write Animal("Cat"), Python creates an object, then runs the __init__ method, storing "Cat" as the species. You don’t need to call __init__ directly—it runs in the background during object creation.
This automatic behavior lets you define what every object should carry from the start.
When you make a new object from a class, Python starts by setting aside space in memory. It then calls __init__, which receives the new object as its first input (self). After that, Python passes along whatever extra arguments you supplied.
Here's what’s happening under the hood:
python
CopyEdit
creature = Animal("Dog")
Is understood by Python as:
python
CopyEdit
Animal.__init__(creature, "Dog")
This flow gives you full control over how the object is structured. You can decide what kind of information each object holds the moment it's made.
Let’s shift to another example:
python
CopyEdit
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
Now, when you run:
python
CopyEdit
c1 = Circle(5)
print(c1.area())
You're not just making a shape—you’re also storing the radius and giving it behavior.
This connection between class and object setup is what makes __init__ so useful.
Each object made from a class can carry its unique data. This is done through instance variables—attributes that belong to a single object. Most of these are assigned to the __init__ method.
Let’s take an example where this matters:
python
CopyEdit
class Laptop:
def __init__(self, brand, model):
self.brand = brand
self.model = model
Each time you make a new laptop object, __init__ assigns the brand and model to that specific object. This lets you track many devices without mixing them up:
python
CopyEdit
l1 = Laptop("Dell", "XPS 13")
l2 = Laptop("Apple", "MacBook Air")
Even though both objects came from the same class, they carry different values. l1.brand and l2.brand will return different results.
You can also build functions inside the class that use these variables:
python
CopyEdit
def get_info(self):
return f"{self.brand} - {self.model}"
This ties the object's data to its behavior, which is one of the main goals of object-oriented programming.
Each instance stays independent, which makes your program more organized and predictable.
There are times when not all the information is available up front. In these cases, default values help. You can set a fallback value so the object still works even if you skip an input.
Let’s consider a signup system:
python
CopyEdit
class User:
def __init__(self, name, country="Unknown"):
self.name = name
self.country = country
This lets you create users even when the country isn’t specified:
python
CopyEdit
u1 = User("Alice")
u2 = User("Bob", "Canada")
The first object will store "Unknown" for the country, while the second will store "Canada". This adds flexibility and avoids errors when inputs are incomplete.
You can also manage more complex structures like lists or dictionaries carefully inside __init__:
python
CopyEdit
class Cart:
def __init__(self, items=None):
if items is None:
self.items = []
else:
self.items = items
It’s common to use None as the default and then assign an empty list inside the method. This avoids sharing the same list across multiple objects, which could lead to accidental data mixing.
Multiple parameters are also easy to manage, and naming them clearly makes your code easier to read:
python
CopyEdit
class Student:
def __init__(self, name, age, grade="Not Assigned"):
self.name = name
self.age = age
self.grade = grade
This setup supports different combinations of input while still assigning meaningful defaults. Each object starts with a complete structure, whether or not all data was provided.
If you want to allow full customization, users of your class can still supply values for all fields. But if they leave something out, your __init__ has a plan.
The __init__ method in Python is used to prepare objects when they’re created. It lets you assign values, manage optional inputs, and build a consistent structure for every object. Instead of setting attributes manually after creation, you can use __init__ to do it automatically. Whether you’re working with text, numbers, or lists, this method gives you full control over how each object starts its life. You can define default values, handle missing data, and keep your class clean and organized. Once you get comfortable with __init__, writing better Python classes becomes easier and your code becomes more efficient, readable, and easier to maintain across larger projects.
Advertisement
Explore the key differences between AI, machine learning, and deep learning with practical insights and use case examples.
Learn how the Python list extend() method works with practical, easy-to-follow examples. Understand how it differs from append and when to use each
Learn 10 clean and effective ways to iterate over a list in Python. From simple loops to advanced tools like zip, map, and deque, this guide shows you all the options
Want to organize your pandas DataFrame without confusion? This guide shows clear, practical ways to sort by values, index, custom logic, or within groups
Highlighting top generative AI tools and real-world examples that show how they’re transforming industries.
Discover top industries for AI contact centers—healthcare, banking fraud detection, retail, and a few others.
Explore how Rabbit R1 enhances enterprise productivity with AI-powered features that streamline and optimize workflows.
How to replace values in a list in Python with 10 easy methods. From simple index assignment to advanced list comprehension, explore the most effective ways to modify your Python lists
Amazon explores AI-generated imagery to create targeted, efficient ads and improve marketing results for brands.
Compare Intel’s AI Gaudi 3 chip with Nvidia’s latest to see which delivers better performance for AI workloads.
Domino Data Lab introduces tools and practices to support safe, ethical, and efficient generative AI development.
Discover Oracle’s GenAI: built-in LLMs, data privacy guarantees, seamless Fusion Cloud integration, and more.