--- title: __init__ in Python - Scaler Topics Description: Learn about the init method in Python by Scaler Topics. Understand its uses, syntax, Inheritance, etc., along with simple examples. author: Shubh Agrawal Category: Python --- :::section{.abstract} ## Overview In an object-oriented approach, the `__init__` method is the Python equivalent of the C++ constructor. Every time an object is created from a class, the `__init__`function is called. The `__init__` method only allows the class to initialize the object's attributes. It is only used within classes. ::: :::section{.main} ## What is __init__ in Python? [Python](https://www.scaler.com/topics/python/) is an object-oriented language. Whenever we create the object of our class, the [the constructor](https://www.scaler.com/topics/constructor-in-python/) of our class is called first. There is a method called `__init__()` for this task in Python. This method is called automatically whenever a new object of a class is created. `__init__` is a magic method called **Dunder** Methods (These are special methods whose invocation happens internally, and they start and end with double underscores). Other examples for magic methods are: `__add__`, `__len__`, `__str__`, etc. :::section{.main} ## How Does the __init__ Method Work? The init method in python is a special method used in the process of initializing an object. When you create a new instance of a class, the __init__ method is automatically called. It simply initialize the class object. ::: :::section{.main} ## Examples of __init__ in Python ### 1. The Default __init__ Constructor Here is an example of a class **Car** that will clarify the functioning of `__init__()`. **Code:** ```Python class Car: def __init__(self, name): self.name = name print("I ran first") def product(self): print("I ran second") return ("Name: " + self.name) C = Car('Audi R8') print(C.product()) ``` **Output:** ```Plaintext I ran first I ran second Name: Audi R8 ``` **Explanation:** You can see in the output the order of print statements that `__init__` is called first. ### 2. __init__ with inheritance [Inheritance](https://www.scaler.com/topics/python/inheritance-in-python/) is a fundamental concept in OOPs. it is the way by which a class inherits the properties of another class. Here, the first class are called the **base class** or parent class, and the second class is called the **derived class** or children class. ![init Function in Python](https://scaler-topics-articles-md.s3.us-west-2.amazonaws.com/init-function-in-python.webp) The derived class can access the properties and methods of their parent class. In other words, the child class inherits all the methods and properties of their parent class and can add more methods and properties that are unique to them(child class) only. Inside a child class, `__init__()` of the parent class can be called to create objects and assign values. Here is an example: **Code:** ```Python class ParentClass: def __init__(self): print("Parent Class") class Child(ParentClass): def __init__(self): ParentClass.__init__(self) print('Child Class') obj = Child() ``` **Output:** ```Plaintext Parent Class Child Class ``` **Explanation:** In the above example, when the object of the Child class is created, `__init__()` of the Child class is called, which first calls the `__init__()` of the ParentClass. `__init__()` of the **ParentClass** prints out *‘Parent Class’* then print inside the **Child** class is executed. ::: ::: :::section{.main} ## Syntax of __init__ in Python **Syntax:** ```Python class Songs: def __init__(self, arguments): # function definition ``` `__init__()` function is defined just like a regular Python function. Self must be the first argument. After that, you can pass arguments of your requirements. The logic of the function comes in the function definition part. ::: :::section{.main} ## Parameters in __init__ in Python It can take any number of arguments in it while the first parameter that will be passed in it will always be **self**. **Code:** ```Python class Trip: def __init__(self, to_city, from_city): self.to_city = to_city self.from_city = from_city def holiday(self): return ("From: " + self.from_city + "\nTo_city: " + self.to_city) T = Trip('India', 'London') print(T.holiday()) ``` **Output:** ```Plaintext From: London To_city: India ``` **Explanation:** In the above example, a class **Trip** is created, and an object **‘T’** is created to invoke the methods and attributes. As soon as the object is created, the`__init__` method is initialized with values **India** and **London**, which are assigned to **to_city** and **from_city**, respectively. The [self keyword](https://www.scaler.com/topics/self-in-python/) represents the current instance of the object. So when the **holiday()** method is run, it prints out the values of **from_city** and **to_city**, which are London and India, respectively. ::: :::section{.main} ## Return Value of __init__ in Python The __init__ method of a class is used to initialize new objects, not create them. As such, it should not return any value. Returning None is correct in the sense that no runtime error will occur, but it suggests that the returned value is meaningful, which it is not. **Code:** ```python class Foo: def __init__(self, str): self.str = str obj = Foo('hello') print(obj.str) Foo.__init__(obj, 'Python') print(obj.str) ``` **Output:** ```Plaintext hello Python ``` ::: :::section{.main} ## Exceptions of __init__ in Python The init method in Python is the constructor for object initialization. It lacks a return value and is prone to TypeError if arguments are missing or exceed expectations. Default parameter values can be set to mitigate this. Attempting to access undefined attributes leads to an AttributeError. The __init__ method is not mandatory, but if defined, it's crucial for proper object setup. ::: :::section{.summary} ## Conclusion This article had a lot of information about the __init__ method in Python. Here is a quick summary * `__init__()` is a special Python method that runs when an object of a class is created. * `__init__()` function is mostly used for assigning values to newly created objects. * `__init__()` is a magic method, which means it is called automatically by Python * `__init__()` can also be invoked manually. * `__init__()` also supports inheritance. ::: :::section{.main} ## See Aslo: - [Constructor in Python](https://www.scaler.com/topics/constructor-in-python/). - [Destructor in Python](https://www.scaler.com/topics/destructor-in-python/). :::