The self
In Python, self
is a conventionally used parameter name in instance methods of a class. It refers to the instance of the class that is calling the method.
When we define a method inside a class in Python, we need to specify the self
parameter as the first parameter of the method. For example:
pythonCopy codeclass MyClass:
def my_method(self, arg1, arg2):
# do something
When we call the my_method()
method on an instance of MyClass
, Python automatically passes the instance itself as the self
parameter. For example:
pythonCopy codeobj = MyClass()
obj.my_method(1, 2) # self is implicitly passed as obj
We can then use the self
parameter inside the method to access and modify the instance variables of the calling object. For example:
pythonCopy codeclass MyClass:
def __init__(self, name):
self.name = name
def my_method(self, arg):
print("Hello,", self.name)
self.name = arg
print("Goodbye,", self.name)
In this example, we define a class MyClass
with an instance variable name
and a method my_method()
that prints a greeting using the current value of name
, and then changes the value of name
to the arg
parameter.
When we create an instance of MyClass
and call my_method()
, Python automatically passes the instance as the self
parameter:
pythonCopy codeobj = MyClass("Alice")
obj.my_method("Bob") # prints "Hello, Alice" and "Goodbye, Bob"
Overall, the self
parameter is a convention in Python that allows us to refer to the instance of a class inside its methods. It is an important aspect of object-oriented programming in Python.
Apply for Python Certification!
https://www.vskills.in/certification/certified-python-developer