Python Self

In our previous tutorial on class and object we have seen class implementation where we have seen by default python self parameter added.

This self parameter will help you to access the properties of the class by forming an instance of the class. These properties are nothing but variables and methods.

In Python, self refers to the instance of a class that is currently being worked with. It is a convention to use self as the first parameter in the definition of methods in a class, so that the method can access the attributes and methods of the instance.

When you create an object of a class in Python, you can call methods and access attributes of that instance using the . (dot) operator. The self parameter is automatically passed to these methods when you call them on an instance, and it refers to the instance itself.

self is typically used as the first parameter in the definition of instance methods in a Python class. It refers to the instance of the class that the method is called on, and allows the method to access and modify the attributes and methods of that instance.

You need not specifically create any instance rather than start using self and access class properties i.e., variables and methods.

Python Self Video Tutorial :

In this video tutorial let us try to see the detailed implementation of self in python.

Create a class Exam

class Exam :

now add a init block of code where we will be having self, marks as parameter.

def __init__(self, marks):
    self.marks = marks

now add a result method to perform a basic comparison using marks and print output.

def result(self):
    if self.marks > 50:
        print("Passed")
    else:
        print("Failed")

And then let us try to make use of this function by creating an object of class Exam and then pass 60 as the initial value for marks.

Using the value 60 comparison is done as below.

student1 = Exam(60)

Here we have just passed 60 as a parameter then what about self ???

No need to implicitly pass self here student1 itself is considered as self here and processed further.

class Exam :

    def __init__(self, marks):
    self.marks = marks
    
    def result(self):
    if self.marks > 50:
        print("Passed")
    else:
        print("Failed")

   student1 = Exam(60)
   student1.result()

output :

Passed

You can try creating multiple objects for the class Exam and provide marks values so to observe the functionality of self keyword.

Note that self is just a convention, and you can technically use any name for this parameter. However, using self is considered good practice in Python.

If you have any query’s in this tutorial on Python Self do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates..

Python Self