init method in python


 __init__ Method

The __init__ method is similar to constructor in C++ and Java. Constructors are used to initialize the object state. Like methods, a constructor also contains collection of statements(instructions) that are executed at the time of object creation. It is run as soon as an object of a class is instantiated.

All classes have a function called __init__() function to assign value to object properties, or other operations that are necessary to do when the object is being created.

The __init__ function is called automatically every time the class is being used to create a new object.

In python  no one class exist without the __init__() method if you do not put the __init__() method in your class the python interpreter put an __init__method(without arguments)in your class.

Example 1.


class Person:

        def __init__(self,name,age):

                    self.name=name

                    self.age=age

p=Person("technicalguptaji",28)

print(p.name)

print(page)

Output

technicalguptaji

28

Example 2.

class Person:

        def __init__(self,name):

                self.name=name

        def say_hi(self):

                print("Hello my name is", self.name)

p=Person("technicalguptaji")

p.say_hi()

Output

Hello my name is technicalguptaji












No comments:

Post a Comment