Table of contents
1.
Introduction 
1.1.
Class
1.2.
Object
1.3.
Self
1.4.
__init__
2.
How Does the __init__ Method Work?
2.1.
Exceptions of __init__ in Python
3.
Frequently Asked Questions
3.1.
What is __init__ method in Python?
3.2.
What is the __init__() method?
3.3.
What is __init__(self) in Python?
4.
Conclusion
Last Updated: Dec 11, 2024
Easy

__init__ and self Method in Python Class

Author GAZAL ARORA
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?
__init__ and self Method in Python Class

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))
You can also try this code with Online Python Compiler
Run Code

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()
You can also try this code with Online Python Compiler
Run Code

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

How Does the __init__ Method Work?

The __init__ method in Python is a special constructor method used to initialize an object when it is created. It allows you to set up the initial state of an object by assigning values to its attributes or executing any required setup logic. The __init__ method is automatically called when a new object is instantiated using a class.

Example:

class Person:
   def __init__(self, name, age):
       self.name = name
       self.age = age
# Creating an object
p = Person("Simran", 25)
print(p.name, p.age)
You can also try this code with Online Python Compiler
Run Code

 

Output: 

Simran 25


In this example, the __init__ method assigns the name and age attributes when a new Person object is created.

Exceptions of __init__ in Python

The __init__ method itself does not return a value (it always returns None), but it can raise exceptions if there are issues during object initialization. Common exceptions include:

TypeError: Raised if the arguments passed during object creation do not match the parameters defined in the __init__ method.
Example:

class Person:
    def __init__(self, age):
        if age < 0:
            raise ValueError("Age cannot be negative")
        self.age = age


AttributeError: Raised if an undefined attribute is accessed or modified within the __init__ method.
Example:

class Person:
    def __init__(self, name):
        self.full_name = name.first_name + " " + name.last_name  # Raises AttributeError if name has no such attributes


ValueError: Raised if invalid values are provided during initialization.
Example:

Proper handling of exceptions within the __init__ method ensures robust and error-free object creation.

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

# Missing the 'age' parameter
p = Person("Simran")  # TypeError: __init__() missing 1 required positional argument

Frequently Asked Questions

What is __init__ method in Python?

The __init__ method is a constructor in Python used to initialize an object's attributes when it is created.

What is the __init__() method?

The __init__() method is a special method in Python automatically invoked during object creation to set up initial attributes.

What is __init__(self) in Python?

__init__(self) is the constructor method in Python classes, where self refers to the instance being initialized with specific attributes.

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