Missing argument self python

Python missing 1 required positional argument: ‘self’ Solution

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.

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.

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:

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

Читайте также:  Компиляция exe в java

To solve this error, we first instantiate an object before we call show_player() :

luke = Hero("Luke", "Mage") luke.show_player()
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!

About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.

What’s Next?

icon_10

Get matched with top bootcamps

icon_11

Ask a question to our community

icon_12

Take our careers quiz

James Gallagher

James Gallagher is a self-taught programmer and the technical content manager at Career Karma. He has experience in range of programming languages and extensive expertise in Python, HTML, CSS, and JavaScript. James has written hundreds of programming tuto. read more

Leave a Reply Cancel reply

appstore2

app_Store1

At Career Karma, our mission is to empower users to make confident decisions by providing a trustworthy and free directory of bootcamps and career resources. We believe in transparency and want to ensure that our users are aware of how we generate revenue to support our platform.

Career Karma recieves compensation from our bootcamp partners who are thoroughly vetted before being featured on our website. This commission is reinvested into growing the community to provide coaching at zero cost to their members.

Читайте также:  Install python module window

It is important to note that our partnership agreements have no influence on our reviews, recommendations, or the rankings of the programs and services we feature. We remain committed to delivering objective and unbiased information to our users.

In our bootcamp directory, reviews are purely user-generated, based on the experiences and feedback shared by individuals who have attended the bootcamps. We believe that user-generated reviews offer valuable insights and diverse perspectives, helping our users make informed decisions about their educational and career journeys.

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.

Select Arrow

Find a top-rated training program

Источник

How to Solve Python missing 1 required positional argument: ‘self’

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’

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:

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 has a charge of ')

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.

Читайте также:  Python with open создать файл

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!

Share this:

Источник

Оцените статью