If you are using Python, then you must have come across the self method as a parameter. It is generally used as one of the first parameters. It is used in method definitions and in variable initialization. The self method is explicitly used every time we define a method.

When to use self in Python?

In object-oriented programming, whenever we define methods for a class, we use self as the first parameter in each case. The self parameter is a reference to the current instance of the class and is used to access variables that belong to the class.

For example,

class check:
    def __init__(self):
        print("Address of self = ", id(self))


obj = check()
print("Address of class object = ", id(obj))

As a result, the output is:
Address of self = 2005436563712
Address of class object = 2005436563712

Here, we use the class check to find out the address of the class object and also the address of self. While doing so we use the self keyword in the process.

As the class is just a blueprint, self gives access to the attributes and methods of each object in python. This allows every object to have its own attributes and methods. Hence, before creating these objects we reference the objects as self while defining the class.

What does self do in Python?

Basically, the self keyword is used to represent the instance of the class. With this keyword, we can access the attributes and methods of the class in python. It connects the attributes with the given arguments.

In Python, we have methods that pass the instance automatically but do not receive them automatically.

For example,

class food:
    def __init__(self, fruit, color):
        self.fruit = fruit
        self.color = color

    def show(self):
        print("fruit is", self.fruit)
        print("color is", self.color)


apple = food("apple", "red")
grapes = food("grapes", "green")

apple.show()
grapes.show()

As a result, the output is:
fruit is apple
color is red
fruit is grapes
color is green

Here, we are creating a class for food and displaying their names and colours. The self keyword helps us to assign the different characteristics to various objects like apple and grapes in the class.

Self in Python Class Constructor

The self keyword is also used to refer to a variable field within the class.
For example,

class Person:
    def __init__(self, Rick):
        self.name = Rick

    def get_person_name(self):
        return self.name

Here, the self keyword refers to the name variable of the entire Person class. If we have a variable within a method, self will not work.

The variable is existent only while that method is running and hence, is local to that method. For defining global fields or the variables of the complete class, we need to define them outside the class methods.

You can also learn about Tree in Python

Like this article? Follow us on Facebook and LinkedIn.