Python self Parameter

self is the reference to the current object that Python passes into every instance method, letting the method read and change that object's own data.

Every method defined in a class receives, as its first parameter, the object it was called on. By convention this parameter is named self. It is how a method knows which particular object it is working with when many objects share the same class. Without self, a method would have no way to reach the attributes that belong to that specific instance.

How self connects a call to an object

When you write obj.method(), Python automatically passes obj as self. That is why you define a method with self in its parameter list but never pass it explicitly at the call site. The two forms below are equivalent, and seeing them side by side makes the mechanism clear.

self is filled in automatically

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

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

c = Counter()

c.increment()              # normal call, self = c
Counter.increment(c)       # explicit form, same effect
print(c.count)             # 2

Using self to store and read data

Attributes attached to self live for as long as the object does, so one method can set a value that another method reads later. Each object keeps its own separate copy of these attributes.

Each object has its own self

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

small = Rectangle(2, 3)
big = Rectangle(10, 5)
print(small.area())   # 6
print(big.area())     # 50
Note: The name self is only a convention, not a keyword, so Python would accept any name in that position. Stick with self anyway; every Python programmer expects it, and using anything else makes code harder to read.
QuestionAnswer
What is self?A reference to the current object
Where is it declared?As the first parameter of an instance method
Do I pass it manually?No, Python supplies it from the object before the dot
Why use it?To access and modify that object's own attributes
  • self refers to the specific object a method is acting on.
  • It is the first parameter of every instance method.
  • Python passes it automatically when you call obj.method().
  • Use self.attribute to store per-object data.