Wed Apr 20 2022·2 min read
Photo by Bella Huang
The Python "TypeError: __init__() should return None, not 'int'" 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
method in a class should always return
Here is an example of how the error occurs.
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary return 100 # 👈️ remove this return statement # ⛔️ TypeError: __init__() should return None, not 'int' emp1 = Employee('Alice', 150)
The error is caused because we returned an integer from the
__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('Alice', 150) print(emp1.name) # 👉️ 'Alice' print(emp1.salary) # 👉️ 150
If we return a value other than
None from a classes'
__init__() method, a
TypeError is raised.
return Nonefrom 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
When a class defines the
__init__() method, the method is invoked when an
instance is created.
__init__() method isn't supposed to return anything.
class Employee(): country = 'Austria' def __init__(self, name, salary): self.name = name self.salary = salary def get_salary(self): return self.salary emp = Employee('Alice', 100) print(emp.name) # 👉️ 100 print(emp.get_salary()) # 👉️ "Alice"
__init__(two underscores on each side).
If you pass arguments when instantiating a class, the arguments are passed on to
salary instance variables in the example above are unique to
each instance, as opposed to the
country class variable which is shared by all
Note that the first argument the
__init__() method takes is
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.