Day - 34 of DevOps

Day - 34 of DevOps

Python Constructor and Self keyword

If you are working with Python, there is no escaping from the word “self”. It is used in method definitions and in variable initialization. The self method is explicitly used every time we define a method. In this article, we will get into the depth of self in Python in the following sequence:

  • What is the use of self in Python?

  • Python Class self Constructor

  • Is self in Python a Keyword?

What is the use of Self in Python?

The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in Python. It binds the attributes with the given arguments.

The reason why we use self is that Python does not use the ‘@’ syntax to refer to instance attributes. In Python, we have methods that make the instance to be passed automatically, but not received automatically.

Python Class self Constructor

When working with classes, it’s important to understand that in Python, a class constructor is a special method named init that gets called when you create an instance (object) of a class. This method is used to initialize the attributes of the object. Keep in mind that the self parameter in the constructor refers to the instance being created and allows you to access and set its attributes. By following these guidelines, you can create powerful and efficient classes in Python.

Example:

class laptop():
    def __init__(self):
        self.RAM="8 GB RAM"

dell=laptop()

print(dell.RAM)

Output:

8 GB RAM

Is self a Keyword?

self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python.

self is a parameter in function and the user can use a different parameter name in place of it. Although it is advisable to use self because it increases the readability of code.

Example: Creating a Class with functions and objects

class laptop():
# init method or constructor    
    def __init__(self):
        self.RAM=""
    def show(self):
        print("RAM: ", self.RAM)
        print("Processor: ", self.processor)

#define 'dell' object inside the 'laptop' class
dell=laptop()


#define vaiables 'RAM' & 'proceesor'
dell.RAM="8 GB RAM"
dell.processor="i7 processor"

#call the function 'show' defined under laptop class
dell.show()

Output:

RAM:  8 GB RAM
Processor:  i7 processor

Example program 1:

class student():
    def __init__(self):
        self.name=""
        self.regno=""
    def display(self):
        print("Name of the student: ", self.name)
        print("Regno of the student: ", self.regno)

s1=student()

s1.name="Gokul"
s1.regno=21

s1.display()

Output:

Name of the student:  Gokul
Regno of the student:  21

Example program 2:

class Fruit():
    def __init__(self, col):
        self.color=col

apple=Fruit("Red")
print(apple.color)

Output:

Red

Congrats🎉, On Learning the Python Constructor and Self keyword.

Happy Learning :)