"This constructor takes no arguments" error in __init__

I'm getting an error while running the following code:

class Person:
  def _init_(self, name):
    self.name = name

  def hello(self):
    print 'Initialising the object with its name ', self.name

p = Person('Constructor')
p.hello()

The output is:

Traceback (most recent call last):  
  File "./class_init.py", line 11, in <module>  
    p = Person('Harry')  
TypeError: this constructor takes no arguments

What's the problem?


Solution 1:

The method should be named __init__ to be a constructor, not _init_. (Note the double underscores.)

If you use single underscores, you merely create a method named _init_, and get a default constructor, which takes no arguments.

Solution 2:

Use double underscores for __init__.

class Person:
  def __init__(self, name):

(All special methods in Python begin and end with double, not single, underscores.)