Home » Python

What __init__ and self do in Python?

Python __init__ and self keywords: Here, we are going to learn about the __init__ and self keywords in Python with examples.
Submitted by Sapna Deraje Radhakrishna, on February 01, 2020

The __init__ and self are two keywords in python, which performs a vital role in the application.

To begin with, it is important to understand the concept of class and object.

Class

In Object-oriented programming, a class is a blueprint for creating objects of a particular data structure, provisioning the initial values for the state, and implementation of a behavior.

The user-defined objects are created using the class keyword.

Object

It is a basic unit of Object-Oriented Programming and each object is an instance of a particular class or subclass with class's methods or procedures and data variables.

With the above understanding,

__init__

__init__ is a reserved method in python classes. It is used to create an object of a class, something like a constructor in Java. This method when called creates an object of the class and it allows the class to initialize the attributes of the class.

Example usage of __init__:

# A Sample class with init method 
class Country:     
    # init method or constructor 
    def __init__(self, name): 
        self.name = name 
    
    # Sample Method 
    def hello(self): 
        print('Hello, my name is', self.name) 
    
c = Country('India') 
c.hello()

Output

Hello, my name is India

In the above example, the line c = Country('India') invokes the method __init__ and creates an object c, which can then further invoke the method hello().

self

The word self is used to represent the instance of the class. Using self, the attributes and the methods of the class can be accessed.

Example usage of self:

class Country:     
    # init method or constructor 
    def __init__(self, name): 
        self.name = name 
    
    # Sample Method 
    def hello(self): 
        print('Hello, my name is', self.name) 

Output

No output

In the above example, name is the attribute of the class Country and it can be accessed by using the self keyword.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.








Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.