Python class __init__ method | Basics

Python class init method is a reserved method in python classes. It represents a constructor in Python. When an object creates it is called and it allows the class to initialize the attributes of a class.

As you know if you know another object-oriented programming constructors are used to initialize the object’s state. It is initialized (assigns values) to the data members of the class when an object of the class is created.

Example __init__ in Python

Simple example code class with the init method in Python.

class Person:

    # init method or constructor   
    def __init__(self, name):
        self.name = name

    # Sample Method
    def greeting(self):
        print('Hello,', self.name)


p = Person('John')
p.greeting()

Output:

Python class init method

Do comment if you have any doubts and suggestions on this Python basic tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.