__init__ Method in Python
In this article we will learn about __init__ Method,Inheritance of __init__ Method,calling __init__ Method.This topic is covered with examples in python.
In Python, the __init__ method is a special method used to initialize objects created from a class. It is called the constructor method because it is called automatically when an instance of a class is created, just like a constructor in other object-oriented programming languages like C++.In this article, we will discuss the __init__ method and understand its use with the help of examples. We will be covering the following sections:
- Introduction to __init__ Method in Python
- Calling __init__ Method in Python
- Inheritance of __init__ Method in Python
- Examples of Using the __init__ Method in Python
Introduction to __init__ Method in Python
The Python __init__ method corresponds to the C++ constructor in an object-oriented approach. Whenever a class generates an object, the __init__ function is invoked, allowing the class to initialize the object’s attributes. The __init__ method is only used inside classes and restricts the class’s ability to initialize the object’s attributes.
The purpose of the __init__ method is to allow the class to set initial values for the attributes of an object when it is first created. This method takes the “self” parameter, which refers to the instance being created, and any additional parameters the class needs to set initial values for the object’s attributes.
The __init__ method can be considered a blueprint for creating objects of a class, allowing the class to define the necessary initial values for the object’s attributes. Once the __init__ method has finished executing, the object is fully initialized and ready for use.
Syntax of __init__
The syntax of __init__ method in Python is given as:
class ClassName: def __init__(self, parameter1, parameter2, ...): self.attribute1 = parameter1 self.attribute2 = parameter2 ...
The __init__() function is defined like a regular python function. Here, ClassName is the name of the class, __init__ is the method’s name, and self is a reference to the instance of the class being created. The parameters parameter1, parameter2, etc., are used to pass initial values to the attributes of the object being created.
Within the __init__ method, the initial values for the object’s attributes are assigned using the self keyword. For example, if the object has an attribute named attribute1, the __init__ method would assign its initial value to self.attribute1.
It is important to note that the __init__ method is optional, but it is typically used in most classes to ensure that objects are properly initialized with the necessary attributes.
Must Check: Python Online Courses & Certificates
Must Check: for loop in Python
Best-suited Python courses for you
Learn Python with these high-rated online courses
Calling __init__ Method in Python
The __init__ method in Python is called automatically whenever a new class object is created. This happens using the class name followed by parentheses that contain any arguments required by the __init__ method.
Here is an example of creating an object of a class and calling its __init__ method:
class Person: def __init__(self, name, age): self.name = name self.age = age
person1 = Person("Alice", 25)
In this example, we define a Person class with two attributes name and age. The __init__ method takes name and age parameters and assigns them to the name and age attributes of the object being created.
To create an object of the Person class, we call the class name followed by parentheses that contain the arguments required by the __init__ method. In this case, we create an object named person1 with the name “Alice” and age 25.
Once the __init__ method has been called, the object is fully initialized with the attributes specified in the __init__ method. We can then access these attributes using dot notation:
print(person1.name) # Output: Aliceprint(person1.age) # Output: 25
Output:
Alice
25
Inheritance of __init__ Method in Python
Inheritance is an important concept in object-oriented programming that allows a new class to be based on an existing class, inheriting its attributes and methods. When a subclass is created, it can also inherit its parent class’s __init__ method.
When a subclass inherits the __init__ method from its parent class, it can extend the initialization process by adding its attributes or modifying the attributes inherited from the parent class. This is done by calling the super() function [insert link] to invoke the parent class’s __init__ method.
An example has been provided in the below section.
More Examples of Using the __init__ Method in Python
Example 1: Simple Class with Single Attribute
class Person: def __init__(self, name): self.name = name
person1 = Person("Alice")print(person1.name) # Output: Alice
person2 = Person("Bob")print(person2.name) # Output: Bob
This example defines a simple class Person with a single attribute name. The __init__ method takes a parameter name and assigns it to the object’s name attribute using self.name = name. We then create two instances of the Person class, person1 and person2, with different names. The output shows that each object has its own unique name attribute.
Example 2: Class with Multiple Attributes
class Rectangle: def __init__(self, length, width): self.length = length self.width = width self.area = length * width
rectangle1 = Rectangle(4, 6)print(rectangle1.length) # Output: 4print(rectangle1.width) # Output: 6print(rectangle1.area) # Output: 24
rectangle2 = Rectangle(5, 10)print(rectangle2.length) # Output: 5print(rectangle2.width) # Output: 10print(rectangle2.area) # Output: 50
In this example, we define a class Rectangle with three attributes: length, width, and area. The __init__ method takes two parameters, length and width, and calculates the area attribute using the formula length * width. We then create two instances of the Rectangle class, rectangle1 and rectangle2, with different lengths and widths. The output shows that each object has its unique length, width, and area attributes.
Example 3: Inheritance with Super()
class Animal: def __init__(self, species): self.species = species
class Dog(Animal): def __init__(self, name, species): super().____init____(species) self.name = name
dog1 = Dog("Fido", "Canis lupus familiaris")print(dog1.name) # Output: Fidoprint(dog1.species) # Output: Canis lupus familiaris
dog2 = Dog("Rover", "Canis lupus familiaris")print(dog2.name) # Output: Roverprint(dog2.species) # Output: Canis lupus familiaris
In this example, we define a class Animal with a single attribute species and a subclass Dog that inherits from Animal. The Dog class has two attributes: name and species. The __init__ method of the Dog class takes two parameters, name and species.
To initialize the species attribute, we use the super() function to call the __init__ method of the parent class Animal. This ensures the species attribute is set correctly before we set the name attribute. We then create two instances of the Dog class, dog1 and dog2, with different names and species. The output shows that each object has its unique name and species attributes.
As you can see, the parent class’s constructor is accessed here using the super() function in the Child class.
Endnotes
Hope this article was helpful for you to understand how and why the __init__ method is used in Python. If you wish to learn more about Python and practice Python programming, you can explore related articles here.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio