TypeError: Class() takes no arguments in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: Class() takes no arguments in Python #

The Python "TypeError: Class() takes no arguments" occurs when we forget to define an __init__() method in a class but provide arguments when instantiating it. To solve the error, make sure to define the __init__() (two underscores on each side) method in the class.

python typeerror class takes no arguments

Here is an example of how the error occurs.

main.py
class Employee(): def get_salary(self): return self.salary # ⛔️ TypeError: Employee() takes no arguments emp = Employee('Alice', 100) print(emp)

We haven't defined an __init__() method but are passing arguments to the class.

To solve the error, make sure to define an __init__() method or correct your spelling if your class already has one.

main.py
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"
Make sure your indentation is correct and you haven't misspelled __init__ (two underscores on each side).

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.

If you pass arguments when instantiating a class, the arguments are passed on to the __init__() method.

The 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.

Conclusion #

The Python "TypeError: Class() takes no arguments" occurs when we forget to define an __init__() method in a class but provide arguments when instantiating it. To solve the error, make sure to define the __init__() (two underscores on each side) method in the class.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.