Self Keyword in Python

The self represents the class instance. We may access the class's properties and methods in Python using the "self" keyword. The keyword associates the properties with the class's arguments provided.

Since Python does not employ the @ syntax to create references to the instance attributes, we must use self. Python opted to implement methods so that the instance of the classes to which the method corresponds is automatically supplied but not immediately received: the first argument of any method is the instance on which the method is executed.

Exploring Object references with self

Example 1 : self keyword program

Code

Output

The reference id of the self method is:  139904481668400
The reference id of the object is:  139904481668400 

Why is the Self Method Defined Every Time?

Even though we understand the purpose of self, it may appear strange, particularly to developers who have learned other programming languages, that self is explicitly supplied as a parameter every time we construct a method. It is believed that explicit is always better than implicit.

Example 2:

We have a Position class which has a method called distance for calculating the distance of the given point from the origin.

Code

Output

The distance of the point (3, 4) from the origin is:  5.0

In the above scenario, __init__() declares three arguments, but we only passed two (3 and 4). Similarly, distance() takes one input but receives none.

Example 3:

Why is the Python interpreter not reporting the mismatched argument numbers? Let's see in the below code.

Code

Output

The name of the student is Harry
The age of the student is 29
Name of the student is Louis
Age of the student is 30
The age of Harry is  29
The age of Louis is  30 

This occurs because after assigning attributes in the function Object() , they are associated with that specific object; in this case, attributes (name, age) are attached to objects (Harry and Louis) when we initialize them.

Example 4:

The self argument must be sent to the Instance function and constructor as the first parameter. It will result in an error if we do not give it.

Code

Output

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in 
      7 
      8 # Creating an instance of the class
----> 9 object_ = Paint()
     10 print("This command shows the instance is created")
     11 

TypeError: __init__() takes 0 positional arguments but 1 was given

How to Avoid Self Parameter?

We can see by now that the class object or instance itself is automatically given over as the first parameter. When creating a static method, this implicit behavior may be prevented. Look at the following basic example:

Code

Output

We did not pass the self parameter to this method

__init__() is not a Constructor

The __init__() function is not a constructor, which is a crucial conclusion from the information. Many inexperienced Python programmers are perplexed by it because __init__() is executed when we build an object.

As we know, the instance itself is the first parameter of the __init__() method. The method __init__() is used to initialize the object right after it is constructed.

In technical terms, a function Object() is a method that builds the object itself. This function is called new () in Python. This method's syntax is:

Syntax

When the __new__() method is invoked, the class itself would be automatically provided as the first parameter (cls).

cls, like self, is only a naming convention. Additionally, the *args and **kwargs parameters are utilized in Python function calls to accept an arbitrary amount of parameters.

While implementing __new__(), keep the following in mind:

  • __new__() is always executed before __init__().
  • The first parameter is the class name, which is implicitly given.
  • __new__() should always return a legitimate object. It is not required, but its primary function is to construct and return a Python object.

Consider the following example:

Code

Output

This is under the new method
The class argument:  <class '__main__.Class'>
The args:  (3, 4)
The kwargs:  {}
This is under the init method

This scenario shows how __new__() is invoked before __init__() (). We can also observe that the class is sent as an argument to __new__() (Point). Lastly, the object is formed using the object base class's __new__() function.

In Python, the base class, i.e., the class from which all subsequent classes are derived, is the object. In the preceding example, we used super() to do this.

Conclusion:

All in all, the self keyword in Python is a show utilized inside class strategies to allude to the case of the actual class. It permits getting to and controlling the occurrence's attributes and strategies. While characterizing techniques inside a class, the self boundary is commonly the principal boundary included, in spite of the fact that it tends to be named diversely whenever wanted.