What does self do in 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)
Related Python job interview questions
How do you split long method signature to multiple lines in the most efficient way?
Python JuniorHow do you split long line to multiple lines in Python?
Python JuniorHow do you install a package using PIP?
Python JuniorHow do you check the currently installed version of PIP?
Python JuniorHow do you install list of packages installed by PIP?
Python Junior