Why use __init__() method?


Can someone explain me why I should use the init() method? After reading some documentation I don’t see the use of it. Please explain with a practical example and usecases

Many thanks!

The __init__ method is roughly what represents a constructor in Python. When you call A() Python creates an object for you, and passes it as the first parameter to the __init__ method. Any additional parameters (e.g., A(24, 'Hello') ) will also get passed as arguments–in this case causing an exception to be raised, since the constructor isn’t expecting them.

More information is here.


Thanks! This example helped me out understandig the init method:

In this code:

class Cat:
    def __init__(self, name):
        self.name = name
    def info(self):
        print 'I am a cat and I am called', self.name

Here __init__ acts as a constructor for the class and when an object is instantiated, this function is called. self represents the instantiating object.

c = Cat('Kitty')

The result of the above statements will be as follows:

I am a cat and I am called Kitty