×

__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 eval() function

Python eval() function The eval() function in Python is used to evaluate the given expression. If the specified expression is a legal Python statement, it will be executed. Syntax eval(expression, globals=None, locals=None) Parameter expression: This parameter represents a String,...

1 minute read.

Python Maurer Rose and Rhodonea Curves

In this tutorial, in Python we will make a Maurer Rose example and Rhodonea Curve example. Before we continue to see what precisely is maurer rose or a rhodonea bend...

10 minutes read.

Python String Negative Indexing

This page contains all the information how to use “Negative indexing“ in Python with the help of using slicing. What is an Index? An index is a numeric value, which is assigned...

3 minutes read.

Creating new Database using Python MySQL

In this article, we are going to discuss how to create a new database by connecting Python and MySQL. What is a Database? The places or memory used to secure highly and...

6 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Python program to find the area of the triangle

Python program to find the area of the triangle This article will discuss how to find the area of a triangle in Python with all three given sides. The area of...

2 minutes read.

How to add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

Python Typing Module

An Introduction to the Typing Module The typing module is introduced in Python version 3.5 and used to provide hinting method types in order to support static type checkers and linters...

10 minutes read.

Iterate through the list in Python

One of the six basic data types of the Python computer language is the list. You must be familiar with the methods and functions that deal with lists in order...

7 minutes read.

Python Marshmallow

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

How to Convert String to List In Python?

How to Convert String to List In Python? We all are familiar with what strings and lists are, let us have a quick revision on them- Strings are a sequence of characters...

4 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.

Anaconda in Python 3

What is Anaconda in Python 3? Anaconda is an open-source package combining Python and R programming languages used for data analytics and processing data. It consists of a huge number of...

4 minutes read.

Find Words in String Python

Python : Python programming language is considered a general purpose; it is a high-level programming language that is not much difficult but easier to learn. Python programming language is rich in...

5 minutes read.

Python Multiprocessing Processor

Python: 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 in a faster way....

4 minutes read.

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.

Python String strip() method

Python String strip() method The string. strip() method in Python removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to...

1 minute read.