What does self do in Python?

Experience Level: Junior
Tags: Python

Answer

The self is used to represent the instance of the class. With this "keyword", you can access the attributes and methods of the class instance from within the class.

Self is a first parameter of constructor or class method. The name self is a common convention, however it any other name can be used provided that the parameter is the first parameter in the method.

When a method is defined as static method (by decorating it using @staticmethod decorator), it doesn't have the self parameter because static method doesn't allow to access instance of a class.

Example:

class MyClass:
    __init__(self):
        self.name = "MyClass Human-readable name"
        self.year = 2145

    def modify_year(self, new_year: int):
        self.year = new_year

    @staticmethod
    def log(message: str):
        print(message)

Python for beginners
Python for beginners

Are you learning Python ? Try our test we designed to help you progress faster.

Test yourself