Skip to main content

The self Parameter

Inside a method, self refers to the particular instance of the class the method is working on.

Through it, you reach the properties and methods that belong to the class.

Note: In every method of the class, self has to come first in the parameter list.

Example

Read a class property through self:

Prompt
Create a Person class with init taking name and age, and a greet method that prints a greeting using self.name.
Output: complete Python program

Why Use self?

self is how Python knows which object's properties you mean. Without it, there would be no way to tell:

Example

Thanks to self, the method works with the object it was called on:

Prompt
Create a Person class with a printname method, create two objects and call printname on each.
Output: complete Python program

self Does Not Have to Be Named "self"

The name itself is not required. Any name will do, as long as that parameter comes first in each method of the class:

Note: Just because you can pick another name does not mean you should. self is the Python convention, and sticking to it makes your code easier for others to read.

Example

Here myobject and abc take the place of self:

Prompt
Create a Person class using custom parameter names (myobject, abc) instead of self.
Output: complete Python program

Accessing Properties with self

Every property of the class is within reach through self:

Example

Read several properties through self:

Prompt
Create a Car class with brand, model, year properties and a display_info method using f-string and self.
Output: complete Python program

Calling Methods with self

self also lets a method call other methods of the same class:

Example

One method calls another through self:

Prompt
Create a Person class where the welcome method calls the greet method using self.
Output: complete Python program