The “TypeError: missing 1 required positional argument: ‘self'” is raised when we try to call a method, included in the class definition, on the class instead of an instance of a class.
Before seeing the details, let’s reproduce this error:
#definition of our class
class Course():
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
#our code raising the error
name = Course.get_name()
Code language: Python (python)
If we try to run this code, the error is triggered:
TypeError: get_name() missing 1 required positional argument: 'self'
Code language: Python (python)
Table of Contents
Why does this error is raised?
When you create the definition of a class, you usually start with the definition of the __init__ function, whose code is run every time you create an instance of a class. In this example, we want to set our instance’s name attribute to the value defined when the instance is created.
#definition of our class class Course(): def __init__(self, name): self.name = name def get_name(self): return self.name
When we execute the get_name() method, it expects a parameter: self. Self actually represents an instance of a class.
#definition of our class
class Course():
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
Code language: Python (python)
Which is why the following code is raising an error: we didn’t initiate an instance; therefore the parameter is missing.
#definition of our class class Course(): def __init__(self, name): self.name = name def get_name(self): return self.name #our code raising the error name = Course.get_name()
How can we fix it?
The fix is easy: you need to initiate an instance of the class you defined to call the method on it. The error will not be raised anymore because the self parameter is available.
#definition of our class
class Course():
def __init__(self, name):
self.name = name
def get_name(self):
return self.name
#create an instance
course = Course('Introduction to Python')
#get the name
name = course.get_name() #Introduction to Python
Code language: Python (python)