friedforfun.com → mean after pain → python class programming → what does self do in python
Posted on by Charles Jennings

What Does Self Do in Python

Illustration of a Python class with a self reference pointing to an instance

In Python, self is a reference to the current instance of a class. It must be the first parameter in instance methods and allows access to instance variables and other methods within the class.

When you define a method inside a class, self is required as the first argument. This makes it explicit that the method operates on a specific instance rather than being static or shared across all instances. Without self, the method cannot access or modify instance-specific data.

For example, in a Car class, self.color refers to the color attribute of that particular car instance. The self parameter helps each car maintains its own state independently.

How Self Works in Practice

Python does not use this like JavaScript or Java. Instead, it uses self as a convention. You can technically name it anything, but using self is mandatory for readability and consistency across the community.

When you call a method on an instance, Python automatically passes the instance as the first argument. For example:

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f"{self.name} says woof!")

Creating an instance:

my_dog = Dog("Buddy")
my_dog.bark()

Internally, Python translates my_dog.bark() to Dog.bark(my_dog). The self parameter receives the my_dog instance, allowing access to self.name.

Types of Methods and Self Usage

Not all methods require self. There are three main types of methods in Python classes:

Method Type Requires self? Use Case
Instance Method Yes Accesses or modifies instance data (e.g., def eat(self))
Class Method No - uses @classmethod Operates on the class itself (e.g., def from_string(cls, data))
Static Method No - uses @staticmethod Independent of class or instance (e.g., def add(a, b))

Only instance methods need self. Class and static methods are called on the class or via instances but don't rely on instance state.

Common Misconceptions and Errors

A frequent mistake is omitting self in method definitions. This causes a TypeError when calling the method:

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):  # Correct
        return 3.14 * self.radius ** 2

    def circumference():  # Wrong - missing self
        return 2 * 3.14 * self.radius  # NameError: name 'self' is not defined

Another error is passing self manually during method calls. You don't write obj.method(self) - Python handles it automatically.

Some developers think self is a keyword like if or for. It's not. It's a naming convention. You can rename it to instance or me, but doing so breaks readability and violates PEP 8 guidelines.

Real-World Example: A Banking Account Class

Consider a BankAccount class that tracks deposits and withdrawals:

class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        print(f"${amount} deposited. New balance: ${self.balance}")

    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient funds.")
        else:
            self.balance -= amount
            print(f"${amount} withdrawn. Balance: ${self.balance}")

Creating two accounts:

account1 = BankAccount("Alice", 1000)
account2 = BankAccount("Bob", 500)

account1.deposit(200)  # Output: $200 deposited. New balance: $1200
account2.withdraw(600)  # Output: Insufficient funds.

Each account holds its own balance and owner. The self variable helps deposit() affects only the instance it was called on.

Why Self Is Not Optional

Without self, Python cannot distinguish between instance data and local variables. Consider this flawed version:

class Point:
    def __init__(x, y):
        x = x  # This creates a local variable, not an instance attribute
        y = y  # Same issue

Calling Point(3, 4) creates an object, but x and y are not stored as instance attributes. The correct version uses self:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

This helps point.x and point.y are accessible later.

Firsthand Experience: Debugging a Missing Self

I once spent 45 minutes debugging a method that returned incorrect values. The root cause was a missing self in a method that accessed an instance attribute. The error message was misleading because the method ran without crashing - it just used a local variable instead of the instance's data. Adding self resolved the issue instantly.

Key Distinction: Self vs. Static Methods

When you don't need instance data, use @staticmethod. This avoids passing self entirely:

class MathUtils:
    @staticmethod
    def add(a, b):
        return a + b

MathUtils.add(3, 4)  # Returns 7 - no instance needed

Using static improves performance slightly and clarifies intent. But if you need to access instance data, self is unavoidable.

Authority References

The official Python documentation states: "The first argument of a method is the instance object." Python.org - Classes. This confirms that self is not optional in instance methods.

PEP 8, the official style guide, recommends using self as the name for the first parameter: "Always use self for the first argument of instance methods." PEP 8 - Function and Method Arguments.

Final Notes

Understanding what self does in Python is essential for writing correct object-oriented code. It enables encapsulation, allows state management per instance, and prevents accidental data sharing.


Related Posts