self reference is used within class methods to refer to the instance of the class itself. It is a conventional name used for the first parameter of instance methods and is automatically passed when the method is called.
When defining a method within a class, the first parameter is typically named
self, although you can technically choose any valid variable name. The
self parameter represents the instance of the class and allows you to access its attributes and invoke other methods on it.
Here’s an example to illustrate the usage of
self within a class:
class MyClass: def __init__(self, value): self.value = value def display(self): print("Value:", self.value) def multiply(self, factor): self.value *= factor # Creating an instance of MyClass obj = MyClass(10) # Accessing instance attribute using self obj.display() # Output: Value: 10 # Invoking a method on the instance obj.multiply(3) # Accessing the modified instance attribute obj.display() # Output: Value: 30
In the example above, the
MyClass class has an
__init__ method that takes a
value parameter and assigns it to the
value attribute of the instance using
display method uses
self.value to access and display the value attribute of the instance. The
multiply method multiplies the
value attribute of the instance by the provided
self within the class methods, you can refer to the instance and access its attributes and methods. It allows you to work with the specific instance of the class on which the method is called, enabling object-oriented programming principles such as encapsulation and data manipulation.