"This constructor takes no arguments" error in __init__

Question:

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?

Asked By: Sagnik Kundu

||

Answers:

Use double underscores for __init__.

class Person:
  def __init__(self, name):

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

Answered By: unutbu

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.

You should use double underscores (__init__)(Dunder or magic methods in python) to declare python constructor.

Basic customization:

__init__ called after the instance has been create by __new__ and use to customize the created object.

Called after the instance has been created (by new()), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an init() method, the derived class’s init() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: super().init([args…]).

Because new() and init() work together in constructing objects (new() to create it, and init() to customize it), no non-None value may be returned by init(); doing so will cause a TypeError to be raised at runtime.

We have two types of Constructor in python:

  • default constructor: which is used when you don’t declare the parameterized constructor. its definition has only one argument which is a reference to the instance being constructed (a.k.a self).
def __init__(self):
    # default constructor 
  • parameterized constructor: which takes other parameters in addition to the self parameter.
def __init__(self, parameters):
    # parameterized constructor 

if you don’t declare parameterized constructor, python uses the default constructor which doesn’t take any parameter. So you passed an argument to default constructor and the exception has been thrown.

How to fix it?

Just declare a parameterized constructor by which you can instantiate your instances.

Python3:

class Person:
    def __init__(self, name):
        self.name = name
Answered By: Phoenix
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.