Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
1.1.
Class
1.2.
Object
1.3.
Self
1.4.
__init__
2.
Frequently Asked Questions
2.1.
What is self in Python class?
2.2.
What is __ init __ method in Python class?
2.3.
Why do we need the __init__.py file in Python?
3.
Conclusion
Last Updated: Mar 27, 2024
Easy

__init__ and self Method in Python Class

Author GAZAL ARORA
0 upvote

Introduction 

In this article, we take a look at the ‘self’ and the ‘__init__’ methods in Python. These are important methods when dealing with classes and objects in Python. Thus before diving into them let us briefly recap our knowledge regarding Class and Object. (Also see Objects and Classes in Python)

Class

A class is a user-defined data type with members and methods that can be accessed only by creating an instance of that class. A class is a blueprint for individual objects with exact behavior in technical terms.

Object

An object is created when a class is instantiated to perform all the functionalities defined in the class. Know What is Object in OOPs here in detail.

Also, see OOPS in PythonFibonacci Series in Python

Self

The term 'self' represents a class instance. In Python, we access attributes and methods of a class by using the "self" keyword. It connects the attributes of the class with the arguments provided.

Python does not use the @ syntax to refer to instance attributes; therefore, you must use self. Python chose to implement methods so that the instance to which the method belongs is automatically supplied but not automatically received: the first parameter of methods is the instance the method is called on.

We can say that the self is always pointing to the Current Object.

Let’s understand with an example:

Example 1:

# Use of self.
class check:
    def __init__(self):
        print("The address of self = ", id(self))

object1 = check()
print("The address of class object = ", id(object1))

Output:

Output

Let’s understand the above-written code.

In the above example, self is passed as a first parameter in __init__  function, and we printed the id of both self and object1. We observed that the output is the same for both; therefore, we can say that self and object1 are referring to the same object.

Points to remember,

  1. Self must be passed as the first parameter to the Instance method and the constructor. Otherwise, it will cause an error.
  2. The word "self" is a convention, not a Python keyword.
  3. self is a parameter in the Instance Method, and the user can use another parameter name in place of it. However, using self is recommended because it improves code clarity and is a good programming practice.

__init__

The __init__ method is the same as constructors in Java and C++. It is a reserved method in the python class. The task of the __init__ method is to initialize (or assign values) the data members of a class when an object of that class is created. 

It is executed whenever a class object is instantiated. It is executed whenever a class object is instantiated. The method can perform any initialization on your object.

Let’s understand with an example:

# A demo class with init method.
class Student:

    # init method.
    def __init__(self, name):
        self.name = name

    def printName(self):
        print('Hi, I am', self.name)

# objects of the Student class. 
object1 = Student('Gazal')
object2 = Student('John')

# Calling printName function of the Student class using an object of that class.
object1.printName()
object2.printName()

Output:

Output

You can compile it with online python compiler.

Let’s understand the above-written code.

In the above example, a student named Gazal is created. "Gazal" is passed as an argument when constructing a student. It is given to the __init__ method to initialize the object. Here, the term self denotes a class instance that binds the class attributes to the provided argument. Similarly, by giving different names as arguments, several objects of the Student class can be created.

Also see, Convert String to List Python

Must Read, python ord

Frequently Asked Questions

What is self in Python class?

The class instance is represented by self. We can access the class's attributes and methods using the "self" keyword in Python. It associates the properties with the arguments provided. Because Python does not use the @ syntax to refer to instance attributes, you must use self.

What is __ init __ method in Python class?

In Python classes, "__init__" is a reserved method. In object-oriented terminology, this is referred to as a constructor. When an object is created for a class, this method is called, and it allows the class to initialize the class's attributes.

Why do we need the __init__.py file in Python?

The __init__.py file informs the Python interpreter that a directory contains Python module code. The file is essentially the constructor of your package or directory without being called such. It specifies how packages or functions will be imported into other files.

Conclusion

In this article, we learned about the two important methods used in Python classes: __init__ and self. It helps users to use the methods defined in a class. 

We learned about their uses and importance in Python classes using examples.

Want to learn Python but don't know where to start?

Start here. Coding Ninjas provide this amazing course on Python. If you are getting into coding and want to build a strong foundation, this course is for you.

Preparing for interviews involving Python  check out these Python Interview Questions for Experts.

Do check out The Interview guide for Product Based Companies as well as some of the Popular Interview Problems from Top companies like Amazon, Adobe, Google, etc. on Coding Ninjas Studio.

Also check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, etc. as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

Live masterclass