logo

Understanding self

In Python classes, self is the first parameter of every method. It refers to the specific object calling the method.

class Counter:
    def __init__(self):
        self.count = 0

    def increment(self):
        self.count += 1

When you call increment(), Python automatically passes the object as self:

c = Counter()
c.increment()  # self refers to c

Without self, you couldn't store data on the object or access it later. It's what connects methods to their object's data.

The name self is a convention, not a keyword. You could use any name, but don't - everyone uses self.

I explain self thoroughly in my Python OOP course.