In Python, self refers to the instance of the class in which a method is defined.
It allows you
to access and manipulate the attributes and methods of the instance inside the class. When
defining methods in a class, self must be the first parameter, even though it's not explicitly
passed when the method is called. Python automatically passes the instance itself as the first
argument.
Explanation of self in a Method:
self gives access to the instance calling the method, allowing the method to access
the instance's attributes or other methods.
The method can perform operations on the instance’s data using self.
Example:
python
Copy code
class Calculator:
def add(self, num1, num2):
return num1 + num2
def multiply(self, num1, num2):
return num1 * num2
In this Calculator class:
The methods add and multiply have the self parameter, which refers to the specific
instance of the Calculator class calling the method.
Using the Class:
python
Copy code
calc = Calculator() # Create an instance of the class
result = calc.add(3, 5) # Calls the add method; no need to pass self
explicitly
print(result) # Output: 8
Why is self Needed?
When you create an instance of a class (e.g., calc = Calculator()), the instance
needs a way to refer to its own data and methods. self is that reference.
For example, you can store instance-specific data using self:
python
Copy code
class Calculator:
def __init__(self, name):
self.name = name # Instance variable using self
def add(self, num1, num2):
return num1 + num2
def describe(self):
return f"This is {self.name}'s calculator"
calc = Calculator("John") # Create an instance with a name
print(calc.describe()) # Output: This is John's calculator
Here, self.name refers to an attribute specific to the instance calc.
Summary:
self refers to the current instance of the class.
It is required as the first argument in any method of a class (though it's passed
automatically by Python).
It allows access to the instance’s attributes and methods.