self method
Understanding the self
Keyword in Python
In Python, the self
keyword is used as a reference to the instance of the class. It is the first parameter in the definition of methods within a class and is passed implicitly when the method is called on an instance of the class. The use of self
allows you to access and modify instance variables and call other methods within the class.
Example
class MyClass:
def __init__(self, value):
self.my_variable = value
def print_variable(self):
print(self.my_variable)
def update_variable(self, new_value):
self.my_variable = new_value
# Creating an instance of the class
obj = MyClass(value=42)
# Accessing instance variable using self
obj.print_variable() # Output: 42
# Updating instance variable using self
obj.update_variable(new_value=99)
obj.print_variable() # Output: 99
In the MyClass
example:
- The
__init__
method is the constructor, and it takesself
as its first parameter along with other parameters. self.my_variable
is an instance variable that is specific to each instance of the class.- The
print_variable
method usesself.my_variable
to access the instance variable and print its value. - The
update_variable
method takes a new value and updates the instance variable.
When an instance method is called, Python automatically passes the instance as the first argument (the self
parameter). This allows you to refer to the instance and its attributes within the class.
Understanding the use of self
is crucial in creating and working with classes in Python. It helps maintain the distinction between class-level attributes and instance-specific attributes.