Skip to content
BENIBIX Learn

this and self

Development🧭 Programming ParadigmsObject-Oriented Programming

Also known as this Keyword, self Parameter, self (Python)

The word a method uses to mean the object it was called on.

Think of it like

It is like saying "me" in class. The word stays the same, but it means whoever says it.

Example

A bark method prints self.name. Called on Rex it says Rex. Called on Bella, the same code says Bella.

Why it matters

Without it, a method could not tell which object's data to use. Every class you write leans on it.

Definition

this and self are words a method uses to mean the object it was called on. JavaScript, Java and C# use this. Python uses self, written as the first parameter of each method. When rex.bark() runs, self is rex. When bella.bark() runs, self is bella. That is how one method can work on many objects.

Example code

python
class Dog:
    def __init__(self, name):
        self.name = name
    def bark(self):
        print(self.name + " says woof")

Dog("Rex").bark()
# Rex says woof
self is the dog the method was called on. Here it is Rex.
When Rex runs bark, self points at Rex. The same method serves every dog.

Common mistake

Leaving out self as the first parameter in Python. The call then fails, saying it got one argument too many.

Key takeaways

  1. 1
    Means this object. Whichever one the method ran on.
  2. 2
    Two spellings. this in most languages, self in Python.
  3. 3
    Reaches the data. Used to read and set properties.