Sobes.tech
Junior

What is self in Python?

sobes.tech AI

Answer from AI

self in Python is the first argument of a class instance method. It represents the instance of the object through which the method was called.

Key features of self:

  • Reference to the instance: Allows access to attributes and calling other methods of that specific instance of the class.
  • Naming convention: self is traditional but not mandatory. Any other name can be used, but self is the common standard, making the code more readable.
  • Automatically passed: When calling an instance method, Python automatically passes a reference to the calling instance as the first argument (self). You do not need to specify it when calling.
  • Absent in static methods and class methods: In static methods (@staticmethod), self is absent because they are not linked to a specific instance. In class methods (@classmethod), the first argument is a reference to the class itself (cls), not an instance.

Example of usage:

class MyClass:
    def __init__(self, value):
        # Assign the passed value to the instance attribute 'value'
        self.value = value

    def print_value(self):
        # Use 'self' to access the 'value' attribute of this instance
        print(f"Value is: {self.value}")

# Create an instance of the class
obj = MyClass(10)

# Call the instance method. Python automatically passes 'obj' as 'self'
obj.print_value()

In this example, self inside the __init__ and print_value methods refers to the object obj. Without self, it would be impossible to access the value attribute that belongs specifically to this MyClass instance.