top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Python __init__() Function

Introduction

Python is among the most common coding platforms present in the industry currently. Ranging from amateurs to professionals, Python is used by everyone to code and design applications for both mobile and web. With such great versatility of the platform, there are certain features that are not so noted among users. One such major aspect is the Init function in Python. This article provides an insight into this concept and its following pointers at length.

Python supports structured as well as object-oriented programming. The object and class are used to carry out object-oriented programming. The class describes the object properties. The constructor method is utilized in object-oriented programming to announce, manipulate and initialize the object, and this method is invoked instantly when an object of the class is built. The Init function in Python acts like the constructor method in Python and it is stated inside the class.

Overview

The _init_ method in Python is an exclusive method applied to initialize objects developed from a class. It is named the constructor method as it is called instantaneously when an instance of a class is built, similar to a constructor in different object-oriented programming languages such as C.

The init method is generally shown as double underscores init or as dunder unit. This is due to its having two underscores on both sides of its nomenclature. Such double underscores exhibit that the method is called and applied internally within Python, with no requirement of its explicit invocation by the object.

This article discusses the Init function in Python and knows its use with the aid of examples.

What Is _Init_ In Python?

The question arises: what is init in python? In python init is a specific method termed as the constructor. It is called automatically when a recent instance (object) of a class is designed. The _init_method enables you to initialize the variables (attributes) of an object.

The following is an example to display the usage of _init_:

section MySection:

    def _init_(self, name, age):
          self.name = name
          self.age = age
    def display_info (self):
           print (f “ Name: {self.name}”)
           print ( f “ Age: {self.age} “)
# Creating an instance of MySection
obj = MySection (“David”, 26)
# Accessing attributes and calling methods
obj.display_info()

Syntax Of _Init_ Function In Python

The init function python syntax is as follows:
_init_(self, [arguments])

The first “self” parameter is utilized to denote the instance of the current class. The rest of the parameters are used to describe the attributes of the class.

In the following example, we design a class Car using a method _init_ that adopts 3 parameters (model, make and year). Code inside the method init allots these values to the respective attributes. So we also develop a method start and a method stop that prints detail regarding the car. When we design an object of the class Car and invoke the start and methods stop, the code within the method _init_ is implemented. View:

class Automobile:
    def _init_ (self, model, make, year):
          self.model = model
          self.make = make
          self.year = year

    def start (self):
           print (f “ Starting {self.model} {self.make} {self.year}”)

    def stop (self):
            print (f “ Stopping {self.model} {self.make} {self.year}”)

automobile = Automobile (“Corolla”, “Toyota”, 2021)

Understanding The Code

Every object could possess its individual values for a class’s attributes. The python init method can be adopted to achieve this functionality. It comprises a function object() { [native code] } that permits a class to hold objects with different values.

It is not required to allude to it as a normal procedure. It is akin to a method inside a class. It is called whenever a new object is created for the class.

Now consider the previous example with the init method python:

The aim is to develop a racing game in Python named “NFS.”

Solution: If you wish to build a racing game in Python termed “NFS,” among the initial things you’ll require to do is create separate cars. Each of the autos you create in the game will possess specific characteristics like speed, color, and various ways like accelerating, shifting gear, breaking, and so forth.

Implementing Code

This concept should display like this upon being coded into the interpreter of Python.

class Car (object):
        def _init_(self, model, company, color, speed_limit):
   self.model = model
   self.company = company
   self.color = color
   self.speed_limit = speed_limit
        def start (self):
   print (“started”)
        def stop (self):
   print (“stopped”)
        def accelerate (self):
   print (“accelerating…”)   
   # accelerator functionality here
        def change_gear (self, gear_type):
       print (“gear changed”)
       # gear related functionality here
# After generating the objects, let’s shift to generate the specific cars in the game
maruti_suzuki = Car (“baleno”, “blue”, “suzuki”, 70)
audi = Car (“A4”, “red”, “audi”, 90)

In the previous example, we built two exclusive car models: the Audi A and the Suzuki Baleno. After effectively building these objects, we can use the init method to initialize them and so ready for the next steps.

In this example, the self method can also be used to signify the different instances of the class and link the attributes to the specified inputs. Utilizing the self method, we can access the methods and properties that we have stated within the class.

Example Of _init_

The python init function is an inbuilt function that is called whenever an object is built. The state for the object is initialized by _init_(). Implying, it is a place where we can establish the attributes of an object.

An example of init in python is the following:

class Person:

    # init method or constructor
    def _init_(self, name):
           self.name = name
    # Sample Method
    def greetings (self):
           print (‘Hello,’, self.name)
p = Person( ‘John’ )
p.greeting()

_init_ With Inheritance

Feature inheritance is the potent one in object-oriented programming. The primary definition is the ability of one class that derives or inherits properties from another class.

Relevance Of Inheritance

It will offer code reusability; writing the same code several times is not needed. It will be useful for you to include new features to the class without altering or modifying them.

The primary significance is it will illustrate actual world interactions.

Suppose we built a class called A,and a subclass will be inherited from class B. The entire subclasses will be instantly inherited from class A.

Example Program

# Example Python program which
# Enforces the _init_ method with
# property named Inheritance
class A(object):
    def _init_(self, other):
         print(“A init called”)
         self.other = other
class B(A):
    def _init_(self, other):
         # Calling init of parent class
  1. _init_(self, other)
      print (“B init called”)
      self.other = other
obj = B(“Something”)

Output

The parent class constructor is called initially in any programming language. However, in the python programming language, calling the parent constructor first is not required. The sequence of calling _to init_ method for a child or parent class will be changed. So, we can mention that it can be performed by calling the child constructor after calling the parent constructor.

Inheritance Of _init_ Method In Python

Inheritance is a key concept in object-oriented programming that permits a new class to be positioned on an available class, inheriting its methods and attributes. When a subclass is built, it can even inherit its parent class’s _init_ method.

As a subclass inherits the init method from its parent class, it can enhance the python class initialization process by inserting its attributes or changing the attributes inherited from the parent class. This is achieved by calling the super() function to call the parent class’s init method.

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 (“Tom”)
print (person2.name)            # Output : Tom

This example describes a simple class Person having a single attribute name. The _init_ method adopts a parameter name and entrusts it to the attribute of the object’s name utilizing self.name = name. We then construct two instances of the Person class, person1 and person2, with separate names. The output displays that every object has its individual specific 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 (5, 6)
print (rectangle1.length) # Output : 5
print (rectangle1.width)  # Output : 6
print (rectangle1.area)         # Output : 30
rectangle2 = Rectangle (6, 10)
print (rectangle2.length)    # Output : 6
print (rectangle2.width)    # Output : 10
print (rectangle2.area)        # Output : 60

This example defines a class Rectangle with 3 attributes: length, width, and area. The _init_ method adopts 2 parameters, length and width, and determines the area attribute utilizing the formula length * width. We then build 2 instances of the Rectangle Class, rectangle1 and rectangle2, with separate lengths and widths. The output displays that every object has its specific length, width, and area attributes.

Conclusion

The “_init_” function in Python is utilized to initialize the value of the object attribute of the class. The “_init_” function also implements the statements that are initialized within the function when the object is constructed. The “_init_()” constructor enters the inheritance class at any position within the function. The details of the def init python function are presented by this article.

FAQs

1. Why do you require the _init_ method in Python?

The _init_ method in a class definition enables us to initialize the instance variables or attributes of all instances in the class. The _init_ method is called each time a new instance of the class is made.

2. Can you have a function in _init_ Python?

Init function is defined similarly to a standard Python function. Self needs to be the first argument. Then, you can approve arguments of your needs. The logic of the function displays in the part on function definition.

3. Can _init_ return a value in Python?

The init method of a class is utilized to initialize new objects, not produce them. So, it should not return any value. Returning None is true in the sense that any runtime error will not occur, but it indicates that the returned value is useful, which it is not.

Leave a Reply

Your email address will not be published. Required fields are marked *