×

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy. This __init__ method is used to create objects and is at the core of object-oriented programming. 

From this content, we will discuss the __init__ method and how it was going to work. 

How is the __init__ Method Going to Work in Python? 

In an object-oriented approach, the __init__ method in python is the same as the C++ constructor. It is a function that will always be called an object created from one of the classes. 

__int__ method will make the class initialize the attributes of an object, and it is only used inside the class and for no other purpose.  

Let us know what the meaning of object-oriented programming is: 

Object-Oriented Programming 

The name itself has "objects," which is defined as a computer programming model that will organize objects rather than logic and functions. These objects must contain data in the form of fields like properties and attributes, and the programming code will be in the form of procedures known as methods. 

For example, if you purchase a car and let it be a CLASS, it could contain many attributes that are OBJECTS like BMW, AUDI, KIA, TATA, and so on, and this price or speed of cars will be one of the attributes. 

We use classes for initializing, declaring, and manipulating objects. Classes act as templates from where objects are created.  

We all know that python programming language is an object-oriented programming language. In python, everything will be treated as an object like functions, tuple, dictionary, set, variables, etc. Consider an example- A Boolean variable belongs to a Boolean class. In other words, an object is a real-world entity.  

Class 

A class is a blueprint for creating objects and acts as a constructor for an object.

We use the "class" keyword for creating a class. 

Example

Class Example: 

x=4  
-->For creating an object for the above example, first, we should create an object named "a1" and can print the value of "x".   
class Example:  
x=4  
a1=Example ()  
print (a1.x)  

Output

 __INIT__ IN PYTHON 

From the above example, we noticed that we created class and object. We inherited class properties and created an object named "a1" and a class named "Example". We get the output "4". 

Example 2 

# An example program of a class using __init__ method   
class Person:   
   # apply __init__ method or constructor in program code  
  def __init__(self, name):   
    self.name = name   
     
  # Sample Method   
  def my_name(self):   
    print('Hii!! my name is', self.name)   
   p = Person('ABC')   
p.my_name()  

Output 

 __INIT__ IN PYTHON 

The above example says that the class named "person," and function named "my_name," and a person named "ABC" is created. While creating a class named Person, the name "ABC" will be passed as an argument, then passed to the __init__ method, which is used to initialize an object. The keyword "self" "is used to represent an instance of a class, and then it will combine the attributes with the arguments given.  

Why are Python Objects Important? 

All data which is in python can be represented as an object. Every object in python can be mutable or immutable based on the data type it holds. For example, lists and dictionaries are mutable because we can change their content without modifying their identity.  

__init__  

__init__ method is equal to constructors in java and c ++. These constructors are used for the initialization of a state of an object. The constructors are used to initialize the data members when an object is created. A constructor contains a block of statements, also called instructions, that execute at the time when an object is created. 

__init__ method will run fast when an object of a class is instantiated.  

Example Program by USING __init__ METHOD 

# A class with the __init__ method is used   
class Person:   
  #Using def keyword applies to init Method or constructor  
  def __init__(self, name):   
    self.name = name   
  # Sample Method is created   
  def my_name(self):   
    print('Hiii..!!, my name is', self.name)   
# Creating different objects    
x1 = Person('QPR')   
x2 = Person('ABC')  
x3 = Person('MNO')   
x1.my_name()   
x2.my_name()  
x3.my_name()   

Output 

 __INIT__ IN PYTHON 

The above example says that the class named "person," and function named "my_name," and a person named "QPR, ABC, MNO" is created. While creating a class named Person, "QPR, ABC, MNO", which are passed as an argument, they are passed to the __init__ method used to initialize an object. To represent the instance of a class, the "self" keyword is used and will merge the attributes with the given arguments. 

__init__ USING INHERITANCE 

Feature inheritance is the powerful one in object-oriented programming. The main definition is the capability of one class that inherits or derives properties from another class.  

Importance of Inheritance 

  1. It will provide code reusability; there is no need to write the same code multiple times. It will be helpful for us to add new features to the class without changing or modifying them. 
  2. The main importance is it will represent real-world relationships. 
  3. Suppose we created a class named A, and a subclass will be inherited from class B. All the subclasses will be automatically inherited from class A.  

Example Program 

# Example Python program which  
# Implements the __init__ method with  
# property called 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  
    A.__init__(self, other)  
    print("B init called")  
    self.other = other     
obj = B("Something")

Output 

 __INIT__ IN PYTHON 

In any programming language, the parent class constructor is called first. But in the python programming language, there is no need to call the parent constructor first. The order of calling __to init__ method for a child or parent class will be modified. So, we can say that it can be done y calling the child constructor after calling the parent constructor.

__init__ Method with Default Parameters

The parameters inside the __init__ method can have default values. That is, we can assign values to the variables of the __init__ method inside the parameters.

Example

class Human: 
  def __init__(self,name,age=33): 
    self.name=name 
    self.age=age 
if __name__=='__main__': 
  human=Human("Hari") 
  print(f"My name is {human.name}. I'm {human.age} years old.") 
__init__ method in python is the same as the C++ constructor 

Output

 __INIT__ IN PYTHON 

The above example shows that we have initialized a default parameter that is "age=33," and we have not initialized any value to the name. We have given a class called "Human". In a print statement, we have given a name and age already declared in the parameters.


Related Topics

Python Comments

In this tutorial, we will discuss the importance of comments in the Python code and how various types of comments can be inserted in the code. Comments are used to describe...

3 minutes read.

Python Debugger

In this tutorial, we will understand what is debugging in general. Then we will realize what the python debugger means and what is the method to perform it. Now, let us...

3 minutes read.

Python String rstrip() method

Python String rstrip() method The string.rstrip() method in Python returns a copy of the string with trailing characters removed. Syntax string.rstrip([chars]) Parameter chars:  This argument represents a string specifying the set of characters to be...

1 minute read.

Drop() Function in Python

Drop() Function: The python programming language consists of various libraries; some of them are pandas and matplotlib. Data scientists mainly use the pandas library to analyze the data more easily and...

3 minutes read.

Python pycountry

What is Pycountry? Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations...

4 minutes read.

Python Time Module

Python contains many files that can be imported into a python code and used whenever we want. One of that modules is the time module. It is a good practice...

6 minutes read.

Python Dictionary fromkeys() method

Python Dictionary fromkeys() method The dictionary.fromkeys() method in Python creates a new dictionary from the given sequence of elements and returns a dictionary with the specified keys and values. Syntax dictionary.fromkeys(sequence[, value]) Parameter sequence- This...

1 minute read.

Python List copy() method

Python List copy () method The list.copy () method returns a shallow copy of the list. Syntax list.copy() Parameter NA Return This function returns the copy for the given list. Example 1 # Python program explaining # the list.copy() method # passing the...

1 minute read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

An Introduction to Mocking in Python

Python Mocking is a testing library. It enables you to substitute portions of your system under test with fake(mock) objects and make assertions about how they were utilized.  The test is...

3 minutes read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

2 minutes read.

Import py file in Python

In Python programming language, a module is a single layer of block of Python code that can be loaded and used by importing into other Python block of code. A module...

4 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

Simple GUI calculator using PyQt5 in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

4 minutes read.

How to Practice Python Programming

Learning python kkis a step towards coding. Python gets one closer to programming languages. It is essential to practice every programming language to become a professional in coding. It is...

4 minutes read.

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in...

3 minutes read.

Python Control Statements

Control statements are under the roof topic of loops and loops in python are defined as iteratively and repeatedly working on source code. Loop control statements are defined as they...

3 minutes read.

PyPi TensorFlow

It is a free open-source library for high-performative numerical computations. The architecture of TensorFlow allows us for easy deployment and computing across a varied number of platforms and from desktops...

3 minutes read.