×

__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

How to Download Python

How to Download Python Python is the most renowned programming language and developers across the globe are working on projects that are made using Python and its libraries. Here we will...

4 minutes read.

Python Read CSV file

The CSV stands for “comma-separated value,” which is defined as a simple file format that is used to store data into a tabular form such as a database or spreadsheet. It is...

7 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images. Imread is an Image reading library. One of the most helpful...

7 minutes read.

Python Dictionary items() method

Python Dictionary items() method The dictionary.items() method in Python returns a view object that displays a list of dictionary's (key, value) tuple pairs. Syntax dictionary.items() Parameter NA Return This method returns a view object, displaying the list...

1 minute read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

Python Fit Transform

In machine learning, fit (), transform(), fit transform () methods are provided by scikit learn package. This package is used in model fitting and data processing. These methods are implemented...

2 minutes read.

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental...

4 minutes read.

Python Dictionary Methods

Python Dictionary Methods Python has a set of built-in methods that dictionary objects can call. All the python dictionary methods are as follow: Methods Description clear() The dictionary.clear() method removes all the elements...

3 minutes read.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

3 minutes read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Python List Methods

Python List Methods Python has a set of built-in methods that you can use on lists or arrays. Following are all of the methods of list objects: Methods Explanation append The list.append() method...

3 minutes read.

Compound Interest GUI Calculator using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Python MySQL Database Connection

In this article, you will be able to understand how to connect to a MySQL database through Python. We generally can use many methods or modules to connect to the database...

6 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

Python Syntax

Python is a strong object-oriented programming language that is simple to learn. Python was created to be a very readable programming language. The syntax of the Python programming language is...

8 minutes read.

Amazon rekognition using python

Amazon recognition service is an AI service which is an image labelling API (Application programming interface). In this article, we shall learn to use the AWS python boto3 module to...

3 minutes read.

Python Printf Style Formating

String objects have one special implicit activity: the % administrator (modulo). This is otherwise called the string designing or interjection administrator. Given design % values (where configuration is a string),...

3 minutes read.