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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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.
Method 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.)
Method 3
You should use double underscores (__init__)(Dunder or magic methods in python) to declare python constructor.
__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
selfparameter.
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0