Last updated: Apr 8, 2024
Reading time·3 min
The Python "TypeError: __init__() should return None, not 'X'" occurs when
we return a value from the __init__()
method in a class.
To solve the error, remove the return
statement from the method because the
__init__
method in a class should always implicitly return None
.
TypeError: __init__() should return None, not 'int'
Here is an example of how the error occurs.
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary # 👇️ Remove this return statement return {'name': name, 'salary': salary} # ⛔️ TypeError: __init__() should return None, not 'dict' emp1 = Employee('Bob', 75)
The error is caused because we returned a value from the __init__()
method.
__init__
method shouldn't have a return
statementThe __init__
method should always return None
(implicitly), so remove the
return statement to solve the error.
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary emp1 = Employee('Bob', 75) print(emp1.name) # 👉️ 'Bob' print(emp1.salary) # 👉️ 75
The __init__
method is used to set the supplied values on the instance and
shouldn't return a value.
If we return a value other than None
from a class's __init__()
method, a
TypeError
is raised.
return None
from the __init__()
method but there is no good reason to do that because all functions and methods that don't explicitly return a value, return None
.When a class defines the __init__()
method, the method is invoked when an
instance is created.
The __init__()
method isn't supposed to return anything.
class Employee(): country = 'Belgium' def __init__(self, name, salary): self.name = name self.salary = salary def get_name(self): return self.name emp1 = Employee('Bob', 75) print(emp1.get_name()) # 👉️ 'Bob' print(emp1.salary) # 👉️ 75
__init__
(two underscores on each side).If you pass arguments when instantiating a class, the arguments are passed on to
the __init__()
method.
name
and salary
instance variables in the example above are unique to each instance, as opposed to the country
class variable which is shared by all instances.Note that the first argument the __init__()
method takes is self
.
You could name this argument anything because the name self
has no special
meaning in Python.
self
represents an instance of the class, so when we assign a variable as
self.my_var = 'some value'
, we are declaring an instance variable - a variable
unique to each instance.
I've also written an article on the purpose of 'return self' from a class method.
You can learn more about the related topics by checking out the following tutorials: