Wed Apr 20 2022·2 min read
Photo by Khamkéo Vilaysing
The Python "TypeError: Class() takes no arguments" occurs when we forget to
__init__() method in a class but provide arguments when
instantiating it. To solve the error, make sure to define the
underscores on each side) method in the class.
Here is an example of how the error occurs.
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
To solve the error, make sure to define an
__init__() method or correct your
spelling if your class already has one.
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).
When a class defines the
__init__() method, the method is invoked when an
instance is created.
__init__() method isn't supposed to return anything.
If you pass arguments when instantiating a class, the arguments are passed on to
salaryinstance variables in the example above are unique to each instance, as opposed to the
countryclass variable which is shared by all instances.
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.