Advertisement
Python makes learning how to code a lot less complicated, but sometimes, you still come across things that seem confusing at first. One of those things is the keyword self inside a class. If you have ever wondered why it's there and what it actually does, you're not alone. The good news is that once you understand it, it feels natural and even helpful. Let's break it down clearly and simply.
When you define a class in Python, the self acts as a reference to the current instance of the class. Think of it like this: whenever you create an object based on the class, the self lets the object keep track of its own data and behaviors.
Without self, it would be almost impossible to differentiate between different objects created from the same class. Each time you use self, you’re telling Python, "I’m talking about this specific object."
For example:
python
CopyEdit
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
Here, self.name and self.breed means that each Dog object will have its own name and breed values. Without self, Python would have no idea where to store these details.
In simple words, the self connects the dots between the object and its properties.
You might have noticed that every method inside a class always has self as its first parameter. It’s not optional. Python does this behind the scenes whenever you call a method on an object.
Let’s see it in action:
python
CopyEdit
my_dog = Dog("Buddy," "Golden Retriever")
print(my_dog.name) # Output: Buddy
When you call my_dog.name, Python is secretly passing my_dog as the self argument to the method. So when you define the method, you need self in there to receive the object.
Another example:
python
CopyEdit
class Calculator:
def add(self, a, b):
return a + b
And using it:
python
CopyEdit
calc = Calculator()
print(calc.add(5, 3)) # Output: 8
Behind the scenes, Python turns calc.add(5, 3) into Calculator.add(calc, 5, 3). That’s why self needs to be the first parameter — it's the actual object being used.
If you skip self in the method definition, Python will get confused and throw an error because it won't know where to attach the data or behavior.
At this point, it’s clear that self is used inside class methods whenever you want to work with the object's attributes or other methods. But do you always need to use it? Let’s see.
You use self when:
For example:
python
CopyEdit
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def full_name(self):
return f"{self.make} {self.model}"
Here, self.make and self.model store the car's information inside the object. And when we call full_name, it uses self.make and self.model again to return the full car name.
You do not use self when you are writing a regular function outside a class or when writing static methods (methods that don't need access to any instance attributes).
Example of a static method:
python
CopyEdit
class Math:
@staticmethod
def add(a, b):
return a + b
Notice how self is not there? That's because add doesn't care about any particular object. It just adds two numbers, which is as simple as that.
So, if you don't need to touch any instance attributes or methods, you can skip self by making the method static.
Even people who've been writing Python code for a while can sometimes slip up when using self. Let's go over a few common mistakes so you can spot and avoid them easily.
One of the most common mistakes is forgetting to put self as the first parameter in the method definition. Example of mistake:
python
CopyEdit
class Cat:
def __init__(name, breed): # Wrong
name = name
breed = breed
Here, Python won't know where to store name and breed because there is no self. The right way is:
python
CopyEdit
class Cat:
def __init__(self, name, breed): # Correct
self.name = name
self.breed = breed
Even if you define self.name properly, if you later refer to it without self, Python will think you’re talking about a local variable and not the object’s attribute.
Example of mistake:
python
CopyEdit
def display_name(self):
print(name) # Wrong
Python will throw an error because the name isn't defined in the local function scope. You need:
python
CopyEdit
def display_name(self):
print(self.name) # Correct
When working with inheritance, self still refers to the instance calling the method, even if the method is inherited from a parent class.
Example:
python
CopyEdit
class Animal:
def speak(self):
print("Some generic sound")
class Dog(Animal):
def bark(self):
print("Woof!")
d = Dog()
d.speak() # Output: Some generic sound
Even though speak was defined in Animal, when you call it from a Dog object, self still refers to the Dog object.
So when you inherit methods, self always points to the instance, not necessarily the class where the method is originally defined.
Understanding how self works in Python classes makes writing and reading object-oriented code much easier. It’s the invisible bridge that connects the object to its attributes and methods. Without it, objects would lose their unique data and behavior. If you remember that self always refers to the object itself, and it always needs to be the first parameter in instance methods, everything clicks into place. Keep practicing, and before long, using self will feel second nature.
Advertisement
Chile uses forest fire detection technology and AI-powered fire warning systems to detect fires early and protect forests
Learn how Automated Machine Learning is transforming the insurance industry with improved efficiency, accuracy, and cost savings
Still puzzled by self in Python classes? Learn how self connects objects to their attributes and methods, and why it’s a key part of writing clean code
Neuro-symbolic AI blends neural learning and symbolic reasoning to create smarter, adaptable systems for a more efficient future
Explore how deep learning transforms industries with innovation and problem-solving power.
Discover why employee AI readiness is fairly low, and explore barriers and strategies to boost workplace AI skill development
IoT and machine learning integration drive predictive analytics, real-time data insights, optimized operations, and cost savings
Restructure DevOps for ML models and DevOps machine learning integration practices to optimize MLOps workflows end-to-end
AI transforms sales with dynamic pricing, targeted marketing, personalization, inventory management, and customer support
Discover the 6 common ways to use the SQL BETWEEN operator, from filtering numbers and dates to handling calculations and exclusions. Improve your SQL queries with these simple tips!
Nvidia stock is soaring thanks to rising AI demand. Learn why Nvidia leads the AI market and what this means for investors
Looking for the best open-source AI image generators in 2025? From Stable Diffusion to DeepFloyd IF, discover 5 free tools that turn text into stunning images