We need to instantiate or call classes in Python before accessing their methods. If we try to access a class method by calling only the class name, we will raise the error “missing 1 required positional argument: ‘self’”.
This tutorial will go through the definition of the error in detail. We will go through two example scenarios of this error and learn how to solve each.
Table of contents
- Missing 1 required positional argument: ‘self’
- Example #1: Not Instantiating an Object
- Solution
- Example #2: Not Correctly Instantiating Class
- Solution
- Summary
Missing 1 required positional argument: ‘self’
We can think of a class as a blueprint for objects. All of the functionalities within the class are accessible when we instantiate an object of the class.
“Positional argument” means data that we pass to a function, and the parentheses () after the function name are for required arguments.
Every function within a class must have “self” as an argument. “self” represents the data stored in an object belonging to a class.
You must instantiate an object of the class before calling a class method; otherwise, self will have no value. We can only call a method using the class object and not the class name. Therefore we also need to use the correct syntax of parentheses after the class name when instantiating an object.
The common mistakes that can cause this error are:
- Not instantiating an object of a class
- Not correctly instantiating a class
We will go through each of the mistakes and learn to solve them.
Example #1: Not Instantiating an Object
This example will define a class that stores information about particles. We will add a function to the class. Functions within classes are called methods, and the method show_particle prints the name of the particle and its charge.
class Particle: def __init__(self, name, charge): self.name = name self.charge = charge def show_particle(self): print(f'The particle {self.name} has a charge of {self.charge}')
To create an object of a class, we need to have a class constructor method, __init__()
. The constructor method assigns values to the data members of the class when we create an object. For further reading on the __init__
special method, go to the article: How to Solve Python TypeError: object() takes no arguments.
Let’s try to create an object and assign it to the variable muon. We can derive the muon object from the Particle class, and therefore, it has access to the Particle methods. Let’s see what happens when we call the show_particle()
method to display the particle information for the muon.
muon = Particle.show_particle()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) muon = Particle.show_particle() TypeError: show_particle() missing 1 required positional argument: 'self'
The code fails because we did not instantiate an object of Particle.
Solution
To solve this error, we have to instantiate the object before we call the method show_particle()
muon = Particle("Muon", "-1") muon.show_particle()
If we run the code, we will get the particle information successfully printed out. This version of the code works because we first declared a variable muon, which stores the information about the particle Muon. The particle Muon has a charge of -1. Once we have an instantiated object, we can call the show_particle() method.
The particle Muon has a charge of -1
Note that when you call a method, you have to use parentheses. Using square brackets will raise the error: “TypeError: ‘method’ object is not subscriptable“.
Example #2: Not Correctly Instantiating Class
If you instantiate an object of a class but use incorrect syntax, you can also raise the “missing 1 required positional argument: ‘self’” error. Let’s look at the following example:
proton = Particle proton.show_particle()
The code is similar to the previous example, but there is a subtle difference. We are missing parentheses! If we try to run this code, we will get the following output:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) proton.show_particle() TypeError: show_particle() missing 1 required positional argument: 'self'
Because we are missing parentheses, our Python program does not know that we want to instantiate an object of the class.
Solution
To solve this problem, we need to add parentheses after the Particle class name and the required arguments name and charge.
proton = Particle("proton", "+1") proton.show_particle()
Once the correct syntax is in place, we can run our code successfully to get the particle information.
The particle proton has a charge of +1
Summary
Congratulations on reading to the end of this tutorial. The error “missing 1 required argument: ‘self’” occurs when you do not instantiate an object of a class before calling a class method. You can also raise this error if you use incorrect syntax to instantiate a class. To solve this error, ensure you instantiate an object of a class before accessing any of the class’ methods. Also, ensure you use the correct syntax when instantiating an object and remember to use parentheses when needed.
To learn more about Python for data science and machine learning, go to the online courses page for Python.
Have fun and happy researching!
I can’t get past the error:
Traceback (most recent call last):
File "C:UsersDomDesktoptesttest.py", line 7, in <module>
p = Pump.getPumps()
TypeError: getPumps() missing 1 required positional argument: 'self'
I examined several tutorials but there doesn’t seem to be anything different from my code. The only thing I can think of is that Python 3.3 requires different syntax.
class Pump:
def __init__(self):
print("init") # never prints
def getPumps(self):
# Open database connection
# some stuff here that never gets executed because of error
pass # dummy code
p = Pump.getPumps()
print(p)
If I understand correctly, self
is passed to the constructor and methods automatically. What am I doing wrong here?
asked Jul 8, 2013 at 19:21
You need to instantiate a class instance here.
Use
p = Pump()
p.getPumps()
Small example —
>>> class TestClass:
def __init__(self):
print("in init")
def testFunc(self):
print("in Test Func")
>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func
gl393
3013 silver badges14 bronze badges
answered Jul 8, 2013 at 19:23
Sukrit KalraSukrit Kalra
32.3k7 gold badges67 silver badges70 bronze badges
0
You need to initialize it first:
p = Pump().getPumps()
answered Jul 8, 2013 at 19:23
JBernardoJBernardo
31.7k10 gold badges89 silver badges114 bronze badges
0
Works and is simpler than every other solution I see here :
Pump().getPumps()
This is great if you don’t need to reuse a class instance. Tested on Python 3.7.3.
answered May 18, 2019 at 9:50
Jay D.Jay D.
1,2423 gold badges15 silver badges26 bronze badges
1
The self
keyword in Python is analogous to this
keyword in C++ / Java / C#.
In Python 2 it is done implicitly by the compiler (yes Python does compilation internally).
It’s just that in Python 3 you need to mention it explicitly in the constructor and member functions. example:
class Pump():
# member variable
# account_holder
# balance_amount
# constructor
def __init__(self,ah,bal):
self.account_holder = ah
self.balance_amount = bal
def getPumps(self):
print("The details of your account are:"+self.account_number + self.balance_amount)
# object = class(*passing values to constructor*)
p = Pump("Tahir",12000)
p.getPumps()
Ghost Ops
1,6902 gold badges12 silver badges23 bronze badges
answered Feb 19, 2019 at 13:21
Tahir77667Tahir77667
2,15816 silver badges15 bronze badges
4
You can call the method like pump.getPumps()
. By adding @classmethod
decorator on the method. A class method receives the class as the implicit first argument, just like an instance method receives the instance.
class Pump:
def __init__(self):
print ("init") # never prints
@classmethod
def getPumps(cls):
# Open database connection
# some stuff here that never gets executed because of error
So, simply call Pump.getPumps()
.
In java, it is termed as static
method.
answered Sep 4, 2020 at 9:23
AtomAtom
2406 silver badges13 bronze badges
1
You can also get this error by prematurely taking PyCharm’s advice to annotate a method @staticmethod. Remove the annotation.
answered Dec 3, 2017 at 15:58
ghersongherson
1392 silver badges9 bronze badges
I got the same error below:
TypeError: test() missing 1 required positional argument: ‘self’
When an instance method had self
, then I called it directly by class name as shown below:
class Person:
def test(self): # <- With "self"
print("Test")
Person.test() # Here
And, when a static method had self
, then I called it by object or directly by class name as shown below:
class Person:
@staticmethod
def test(self): # <- With "self"
print("Test")
obj = Person()
obj.test() # Here
# Or
Person.test() # Here
So, I called the instance method with object as shown below:
class Person:
def test(self): # <- With "self"
print("Test")
obj = Person()
obj.test() # Here
And, I removed self
from the static method as shown below:
class Person:
@staticmethod
def test(): # <- "self" removed
print("Test")
obj = Person()
obj.test() # Here
# Or
Person.test() # Here
Then, the error was solved:
Test
In detail, I explain about instance method in my answer for What is an «instance method» in Python? and also explain about @staticmethod and @classmethod in my answer for @classmethod vs @staticmethod in Python.
answered Nov 15, 2022 at 15:19
If skipping parentheses for the object declaration (typo), then exactly this error occurs.
# WRONG! will result in TypeError: getPumps() missing 1 required positional argument: 'self'
p = Pump
p.getPumps()
Do not forget the parentheses for the Pump object
# CORRECT!
p = Pump()
p.getPumps()
answered Nov 21, 2022 at 9:52
Daniel NelsonDaniel Nelson
1,6881 gold badge11 silver badges11 bronze badges
Python classes need to be instantiated, or called, before you can access their methods. If you forget to instantiate an object of a class and try to access a class method, you encounter an error saying “missing 1 required positional argument: ‘self’”.
In this guide, we talk about what this error means and why it is raised. We walk through an example of this error in action to help you learn how to fix it.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
missing 1 required positional argument: ‘self’
Positional arguments refer to data that is passed into a function. In a class, every function must be given the value “self”. The value of “self” is similar to “this” in JavaScript. “self” represents the data stored in an object of a class.
When you call a class method without first instantiating an object of that class, you get an error. This is because “self” has no value until an object has been instantiated.
The most common mistakes that are made that cause the “missing 1 required positional argument: ‘self’” error are:
- Forgetting to instantiate an object of a class
- Using the incorrect syntax to instantiate a class
Let’s walk through each of these causes individually.
Cause #1: Forgetting to Instantiate an Object
An object must be instantiated before you can access a method in a class.
Define a class that stores information about a hero in a video game:
class Hero: def __init__(self, name, player_type): self.name = name self.player_type = player_type
Next, we add a function to our class. Functions inside of classes are called methods. This method prints out the name of a player and their player type:
def show_player(self): print("Player Name: " + self.name) print("Player Type: " + self.player_type)
Try to access our class so that we can create a player:
luke = Hero.show_player()
We have created an object that is assigned to the variable “luke”. This object is derived from the Hero class. We call the show_player()
method to show information about the player.
Let’s run our code altogether and see what happens:
Traceback (most recent call last): File "main.py", line 10, in <module> luke = Hero.show_player() TypeError: show_player() missing 1 required positional argument: 'self'
Our code fails. This is because we have not instantiated an object of Hero. Hero.show_player()
does not work because we haven’t created a Hero whose information can be displayed.
To solve this error, we first instantiate an object before we call show_player()
:
luke = Hero("Luke", "Mage") luke.show_player()
Run our code again:
Player Name: Luke Player Type: Mage
Our code runs successfully! We’ve first declared a variable called “luke” which stores information about a player called Luke. Luke’s player type is “Mage”. Now that we have instantiated that object, we can call the show_player()
method.
Cause #2: Incorrectly Instantiating a Class
The “missing 1 required positional argument: ‘self’” error can occur when you incorrectly instantiate a class. Consider the following code:
luke = Hero luke.show_player()
While this code is similar to our solution from the last example, it is incorrect. This is because we have not added any parenthesis after the word Hero. By missing these parentheses, our program does not know that we want to instantiate a class.
Solve this problem by adding parenthesis after Hero and specifying the required arguments, “name” and “player_type”:
luke = Hero("Luke", "Mage") luke.show_player()
Our code now runs successfully and returns information about our player:
Player Name: Luke Player Type: Mage
Conclusion
The “missing 1 required positional argument: ‘self’” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.
To solve this error, make sure that you first instantiate an object of a class before you try to access any of that class’ methods. Then, check to make sure you use the right syntax to instantiate an object.
Now you’re ready to solve this common error like an expert Python developer!
I can’t get past the error:
Traceback (most recent call last):
File "C:UsersDomDesktoptesttest.py", line 7, in <module>
p = Pump.getPumps()
TypeError: getPumps() missing 1 required positional argument: 'self'
I examined several tutorials but there doesn’t seem to be anything different from my code. The only thing I can think of is that Python 3.3 requires different syntax.
class Pump:
def __init__(self):
print("init") # never prints
def getPumps(self):
# Open database connection
# some stuff here that never gets executed because of error
pass # dummy code
p = Pump.getPumps()
print(p)
If I understand correctly, self
is passed to the constructor and methods automatically. What am I doing wrong here?
asked Jul 8, 2013 at 19:21
You need to instantiate a class instance here.
Use
p = Pump()
p.getPumps()
Small example —
>>> class TestClass:
def __init__(self):
print("in init")
def testFunc(self):
print("in Test Func")
>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func
gl393
3013 silver badges14 bronze badges
answered Jul 8, 2013 at 19:23
Sukrit KalraSukrit Kalra
32.3k7 gold badges67 silver badges70 bronze badges
0
You need to initialize it first:
p = Pump().getPumps()
answered Jul 8, 2013 at 19:23
JBernardoJBernardo
31.7k10 gold badges89 silver badges114 bronze badges
0
Works and is simpler than every other solution I see here :
Pump().getPumps()
This is great if you don’t need to reuse a class instance. Tested on Python 3.7.3.
answered May 18, 2019 at 9:50
Jay D.Jay D.
1,2423 gold badges15 silver badges26 bronze badges
1
The self
keyword in Python is analogous to this
keyword in C++ / Java / C#.
In Python 2 it is done implicitly by the compiler (yes Python does compilation internally).
It’s just that in Python 3 you need to mention it explicitly in the constructor and member functions. example:
class Pump():
# member variable
# account_holder
# balance_amount
# constructor
def __init__(self,ah,bal):
self.account_holder = ah
self.balance_amount = bal
def getPumps(self):
print("The details of your account are:"+self.account_number + self.balance_amount)
# object = class(*passing values to constructor*)
p = Pump("Tahir",12000)
p.getPumps()
Ghost Ops
1,6902 gold badges12 silver badges23 bronze badges
answered Feb 19, 2019 at 13:21
Tahir77667Tahir77667
2,15816 silver badges15 bronze badges
4
You can call the method like pump.getPumps()
. By adding @classmethod
decorator on the method. A class method receives the class as the implicit first argument, just like an instance method receives the instance.
class Pump:
def __init__(self):
print ("init") # never prints
@classmethod
def getPumps(cls):
# Open database connection
# some stuff here that never gets executed because of error
So, simply call Pump.getPumps()
.
In java, it is termed as static
method.
answered Sep 4, 2020 at 9:23
AtomAtom
2406 silver badges13 bronze badges
1
You can also get this error by prematurely taking PyCharm’s advice to annotate a method @staticmethod. Remove the annotation.
answered Dec 3, 2017 at 15:58
ghersongherson
1392 silver badges9 bronze badges
I got the same error below:
TypeError: test() missing 1 required positional argument: ‘self’
When an instance method had self
, then I called it directly by class name as shown below:
class Person:
def test(self): # <- With "self"
print("Test")
Person.test() # Here
And, when a static method had self
, then I called it by object or directly by class name as shown below:
class Person:
@staticmethod
def test(self): # <- With "self"
print("Test")
obj = Person()
obj.test() # Here
# Or
Person.test() # Here
So, I called the instance method with object as shown below:
class Person:
def test(self): # <- With "self"
print("Test")
obj = Person()
obj.test() # Here
And, I removed self
from the static method as shown below:
class Person:
@staticmethod
def test(): # <- "self" removed
print("Test")
obj = Person()
obj.test() # Here
# Or
Person.test() # Here
Then, the error was solved:
Test
In detail, I explain about instance method in my answer for What is an «instance method» in Python? and also explain about @staticmethod and @classmethod in my answer for @classmethod vs @staticmethod in Python.
answered Nov 15, 2022 at 15:19
If skipping parentheses for the object declaration (typo), then exactly this error occurs.
# WRONG! will result in TypeError: getPumps() missing 1 required positional argument: 'self'
p = Pump
p.getPumps()
Do not forget the parentheses for the Pump object
# CORRECT!
p = Pump()
p.getPumps()
answered Nov 21, 2022 at 9:52
Daniel NelsonDaniel Nelson
1,6881 gold badge11 silver badges11 bronze badges
I can’t get past the error:
Traceback (most recent call last):
File "C:UsersDomDesktoptesttest.py", line 7, in <module>
p = Pump.getPumps()
TypeError: getPumps() missing 1 required positional argument: 'self'
I examined several tutorials but there doesn’t seem to be anything different from my code. The only thing I can think of is that Python 3.3 requires different syntax.
class Pump:
def __init__(self):
print("init") # never prints
def getPumps(self):
# Open database connection
# some stuff here that never gets executed because of error
pass # dummy code
p = Pump.getPumps()
print(p)
If I understand correctly, self
is passed to the constructor and methods automatically. What am I doing wrong here?
asked Jul 8, 2013 at 19:21
You need to instantiate a class instance here.
Use
p = Pump()
p.getPumps()
Small example —
>>> class TestClass:
def __init__(self):
print("in init")
def testFunc(self):
print("in Test Func")
>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func
gl393
3013 silver badges14 bronze badges
answered Jul 8, 2013 at 19:23
Sukrit KalraSukrit Kalra
32.3k7 gold badges67 silver badges70 bronze badges
0
You need to initialize it first:
p = Pump().getPumps()
answered Jul 8, 2013 at 19:23
JBernardoJBernardo
31.7k10 gold badges89 silver badges114 bronze badges
0
Works and is simpler than every other solution I see here :
Pump().getPumps()
This is great if you don’t need to reuse a class instance. Tested on Python 3.7.3.
answered May 18, 2019 at 9:50
Jay D.Jay D.
1,2423 gold badges15 silver badges26 bronze badges
1
The self
keyword in Python is analogous to this
keyword in C++ / Java / C#.
In Python 2 it is done implicitly by the compiler (yes Python does compilation internally).
It’s just that in Python 3 you need to mention it explicitly in the constructor and member functions. example:
class Pump():
# member variable
# account_holder
# balance_amount
# constructor
def __init__(self,ah,bal):
self.account_holder = ah
self.balance_amount = bal
def getPumps(self):
print("The details of your account are:"+self.account_number + self.balance_amount)
# object = class(*passing values to constructor*)
p = Pump("Tahir",12000)
p.getPumps()
Ghost Ops
1,6902 gold badges12 silver badges23 bronze badges
answered Feb 19, 2019 at 13:21
Tahir77667Tahir77667
2,15816 silver badges15 bronze badges
4
You can call the method like pump.getPumps()
. By adding @classmethod
decorator on the method. A class method receives the class as the implicit first argument, just like an instance method receives the instance.
class Pump:
def __init__(self):
print ("init") # never prints
@classmethod
def getPumps(cls):
# Open database connection
# some stuff here that never gets executed because of error
So, simply call Pump.getPumps()
.
In java, it is termed as static
method.
answered Sep 4, 2020 at 9:23
AtomAtom
2406 silver badges13 bronze badges
1
You can also get this error by prematurely taking PyCharm’s advice to annotate a method @staticmethod. Remove the annotation.
answered Dec 3, 2017 at 15:58
ghersongherson
1392 silver badges9 bronze badges
I got the same error below:
TypeError: test() missing 1 required positional argument: ‘self’
When an instance method had self
, then I called it directly by class name as shown below:
class Person:
def test(self): # <- With "self"
print("Test")
Person.test() # Here
And, when a static method had self
, then I called it by object or directly by class name as shown below:
class Person:
@staticmethod
def test(self): # <- With "self"
print("Test")
obj = Person()
obj.test() # Here
# Or
Person.test() # Here
So, I called the instance method with object as shown below:
class Person:
def test(self): # <- With "self"
print("Test")
obj = Person()
obj.test() # Here
And, I removed self
from the static method as shown below:
class Person:
@staticmethod
def test(): # <- "self" removed
print("Test")
obj = Person()
obj.test() # Here
# Or
Person.test() # Here
Then, the error was solved:
Test
In detail, I explain about instance method in my answer for What is an «instance method» in Python? and also explain about @staticmethod and @classmethod in my answer for @classmethod vs @staticmethod in Python.
answered Nov 15, 2022 at 15:19
If skipping parentheses for the object declaration (typo), then exactly this error occurs.
# WRONG! will result in TypeError: getPumps() missing 1 required positional argument: 'self'
p = Pump
p.getPumps()
Do not forget the parentheses for the Pump object
# CORRECT!
p = Pump()
p.getPumps()
answered Nov 21, 2022 at 9:52
Daniel NelsonDaniel Nelson
1,6881 gold badge11 silver badges11 bronze badges
In Python, we first need to initialize an object for a class before we call any of the methods defined inside the class. Although we can access the class variables using the class name followed by the dot operator and variable name, if we try to access a class method using the class name, we will encounter the »
TypeError: Method_Name() missing 1 required positional argument: 'self'
» Error.
In this Error guide, we will discuss this error in detail and learn why it raises in a Python program. We will also walk through some common examples where many Python learners encounter this error.
So without further ado, let’s get started with the Error statement.
A Class is a blueprint for objects, and a
class
all functionalities comes into existence when we initialize its objects. If there is a method inside a class we can only call that method using the class object, not with the class name.
This is because, in Python class, all methods have a fixed argument value
self
(conventional name), that represents the object which is calling the method. And when we call the method using the class name we receive the error
TypeError: Method_Name() missing 1 required positional argument: 'self'
. Now let’s break the Error statement into two parts.
- TypeError
- Method_Name() missing 1 required positional argument: ‘self’
1. TypeError
TypeError is a standard Python exception, and it is raised in a Python program when we perform an operation or call a function/method on an inappropriate Python data object.
2. Method_Name() missing 1 required positional argument: ‘self’
This is the error message, which is raised in a Python program when we try to call a method using the class name. We can only call a class method using its object. All class methods have a fixed argument
self
, that needs to be pass to the method when the method is called. And the value of
self
can only be passed to the method when the method is called with the help of the class object this is because the class object is the value for the
self
attribute.
Common Example Scenario
There are two most common cases when you might encounter this error in Your Python program.
- Calling a method using Class Name
- Incorrect Initialization of class Object
1. Calling a method using a Class Name
The core reason why we receive this error occurs is when we use the class name to call a method rather than the object name.
Example
class Human:
def __init__(self):
self.species = "Homo sapiens"
self.avg_age = "79 years"
def show_data(self):
print("Species Name: ", self.species)
print("Average Age of a Human: ", self.avg_age)
Human.show_data()
Output
Traceback (most recent call last):
File "main.py", line 11, in
Human.show_data()
TypeError: show_data() missing 1 required positional argument: 'self'
Break the code
In the above example, we are getting this error because we are calling the
show_data()
method using the class name
Human
. When a method is invoked it expect the value for the
self
attribute, and it can only be satisfied when an object of the class call the method. Because the object which is calling the method becomes the value for the
self
attribute.
Solution
To solve the above method, we first need to initialize the object for the
Human
class, then we can use that object name to call the
show_data()
method.
class Human:
def __init__(self):
self.species = "Homo sapiens"
self.avg_age = "79 years"
def show_data(self):
print("Species Name: ", self.species)
print("Average Age of a Human: ", self.avg_age)
# initialize object
human = Human()
# access method using object name
human.show_data()
Output
Species Name: Homo sapiens
Average Age of a Human: 79 years
2. Incorrect Initialization of class Object
This error also occurs when we do not properly initialize the object for a class. When we initialize or declare a class object we write the object name, followed by the assignment operator Class name and a set of parenthesis after the class name. And if we forget to put the parenthesis, it will not initialize the class instead it will provide an alternative name to the class.
Example
class Human:
def __init__(self):
self.species = "Homo sapiens"
self.avg_age = "79 years"
def show_data(self):
print("Species Name: ", self.species)
print("Average Age of a Human: ", self.avg_age)
# forget to put () after class name
human = Human
# access method using object name
human.show_data()
Output
Traceback (most recent call last):
File "main.py", line 15, in
human.show_data()
TypeError: show_data() missing 1 required positional argument: 'self'
Break the Code
In this example, we are also getting the same error. This is because in line 12 when we are initializing the object for the Human class, we forgot to put the parenthesis
()
after the class name »
human = Human
» .
The statement
human = Human
did not create the object
human
instead it simply provides the alternative name to the
Human
class. At this point both
Human
and
human
are the same. And we know what error occur when we call a method using the class name.
Solution
o solve the above example all we need to do is properly initialize the object for the Human class.
class Human:
def __init__(self):
self.species = "Homo sapiens"
self.avg_age = "79 years"
def show_data(self):
print("Species Name: ", self.species)
print("Average Age of a Human: ", self.avg_age)
# put () after class name
human = Human()
# access method using object name
human.show_data()
Output
Species Name: Homo sapiens
Average Age of a Human: 79 years
Wrapping Up!
In this Python error we discussed one of the most common Python errors » TypeError: method_name() missing 1 required positional argument: ‘self'». This error is raised in a Python program when we call a class method with the help of the class name. To solve this error, make sure that you have initialized the class object properly before calling the method on that object. In most cases, you will be encountering this error when you haven’t declared the object correctly.
If you are still getting this error in your Python program, you can share your code and query in the comment section. We will try to help you in debugging.
People are also reading:
-
Python TypeError: cannot unpack non-iterable NoneType object Solution
-
Function Argument in Python
-
Python TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘str’ Solution
-
Arrays in Python
-
Python RecursionError: maximum recursion depth exceeded while calling a Python object
-
Dictionary in Python
-
Python TypeError: ‘float’ object is not subscriptable Solution
-
Tuple in Python
-
Python typeerror: ‘list’ object is not callable Solution
-
List Comprehension in Python
- Not Instantiating an Object in Python
- Incorrectly Instantiating a Class Object in Python
- Fix the
TypeError: missing 1 required positional argument: 'self'
Error in Python - Conclusion
Classes are one of the fundamental features of Object-Oriented Programming languages. Every object belongs to some class in Python.
We can create our class as a blueprint to create objects of the same type. We use the class
keyword to define a class in Python.
A very important feature in Python is using the self
attribute while defining classes. The self
attribute represents the object’s data and binds the arguments to the object.
This tutorial will discuss the TypeError: missing 1 required positional argument: 'self'
error in Python and how we can solve it.
Let us discuss the situations where this error is raised.
Not Instantiating an Object in Python
Positional arguments refer to the data we provide a function with. For creating class objects, we use a constructor.
If the class requires any data, we must pass it as arguments in the constructor function.
This error is raised when we forget to instantiate the class object or wrongly instantiate the class instance.
See the code below.
class Delft:
def __init__(self, name):
self.name = name
def fun(self):
return self.name
m = Delft.fun()
print(m)
Output:
TypeError: fun() missing 1 required positional argument: 'self'
In the above example, we get the error because we forget to instantiate the instance of the class and try to access the function of the class. As a result, the self
attribute is not defined and cannot bind the attributes to the object.
Note that this is a TypeError
, which is raised in Python while performing some unsupported operation on a given data type. It is not supported to directly access the class method without creating an instance.
Incorrectly Instantiating a Class Object in Python
Another scenario where this error can occur is when we incorrectly instantiate the class object. This can be a small typing error like ignoring the parentheses or not providing the arguments.
For example:
class Delft:
def __init__(self, name):
self.name = name
def fun(self):
return self.name
m = Delft
a = m.fun()
print(a)
Output:
TypeError: fun() missing 1 required positional argument: 'self'
Let us now discuss how to fix this error in the section below.
Fix the TypeError: missing 1 required positional argument: 'self'
Error in Python
To fix this error, we can create the class instance and use it to access the class method.
See the code below.
class Delft:
def __init__(self, name):
self.name = name
def fun(self):
return self.name
m = Delft('Stack')
a = m.fun()
print(a)
Output:
In the example, we first create an instance of the class. This is then used to access the class method to return some value and print it; the error is fixed.
Another fix involves the use of static methods. Static methods are functions bound to a particular class and not to an object.
We can use the @staticmethod
decorator to create such methods.
For example:
class Delft:
def __init__(self, name):
self.name = name
@staticmethod
def fun(abc):
return abc
a = Delft.fun('Stack')
print(a)
Output:
In the above example, we changed the fun()
function to a static function. This way, we could use it without instantiating any class objects.
Conclusion
This tutorial discussed the TypeError: missing 1 required positional argument: 'self'
error in Python and how we can solve it.
We discussed situations where this error might occur and how to fix the error by instantiating the object of the class. We can also use static methods to work around this error.