"This constructor takes no arguments" error in __init__
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
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.
Use double underscores for __init__
.
class Person:
def __init__(self, name):
(All special methods in Python begin and end with double, not single, underscores.)