Python name self is not defined

Python NameError: name ‘self’ is not defined Solution

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.

In this guide, we talk about what this error means and why it is raised. We walk through a few code snippets to help you figure out how to solve this error in your code.

NameError: name ‘self’ is not defined

The “self” variable holds information about an object inside a class. All of the values that have been assigned to an object are available in the “self” variable.

“self” must be passed as an argument if you want to use it in a method. The “self” variable cannot be used in other arguments in a method because it is only accessible from within a method.

You encounter the “NameError: name ‘self’ is not defined” error if you:

Читайте также:  Python json сериализация объекта

Let’s walk through each of these scenarios one-by-one.

Scenario #1: “self” is Not Listed as an Argument

“self” must be listed as an argument for it to be accessible in a method. “self” is not a global variable. It is local inside a class.

Write a program that holds information about movies in a class. We start by defining our class with a constructor that holds values about our movie:

class Movie: def __init__(self, name, year_released): self.name = name self.year_released = year_released

Our class can hold two values: the name of a movie and the year in which it was released. Next, we declare a method that lets us change the value of “year_released”:

def change_year(year_released): self.year_released = year_released print("<> was released in <>.".format(self.name, self.year_released))

To test our code, we create an object of our class. This object represents the movie Happy Gilmore, released in 1996:

happy_gilmore = Movie("Happy Gilmore") happy_gilmore.change_year(1996)

We have called the change_year() method on our object so that we can set the year the movie was released to 1996. Let’s run our code and see if it works:

Traceback (most recent call last): File "main.py", line 11, in happy_gilmore.change_year() File "main.py", line 7, in change_year self.year_released = year_released NameError: name 'self' is not defined

Our code returns an error.

This error is raised because we haven’t passed “self” as an argument to our method. We fix this error by adding “self” as the first argument in the change_year() method:

def change_year(self, year_released): self.year_released = year_released print("<> was released in <>.".format(self.name, self.year_released))
Happy Gilmore was released in 1996.

Our code runs successfully!

Scenario #2: Using “self” as an Argument in Another Argument

“self” is evaluated when a function is called. This means that you cannot have an argument that refers to “self” in the list of arguments specified in a function call.

Update our “year_released” method so that, if a different year of release is not specified, a message is printed to the console telling us that the year of a movie has not been changed.

We can do this by setting a default argument in our code:

def change_year(self, year_released=self.year_released): if year_released != self.year_released: self.year_released = year_released print("<> was released in <>.".format(self.name, self.year_released)) else: print("This movie has not been changed.") print(year_released)

“year_released” now has the default value of “self.year_released”. This means if we do not specify a value to which the year should be changed, a default value is set. If we do specify a value, the value we specify is used instead of the default.

If the value we specify is not equal to the value of “self.year_released”, the value of “self.year_released” is changed. Otherwise, a message is printed to the console telling the user that the movie has not been changed.

After our if statement has been evaluated, the value of “year_released” is printed to the console.

Traceback (most recent call last): File "main.py", line 1, in class Movie: File "main.py", line 6, in Movie def change_year(self, year_released=self.year_released): NameError: name 'self' is not defined

Our code raises an error. This is because we’ve tried to use “self” in another argument in our list of arguments.

We can fix this error by setting the value of the “year_released” variable to “self.year_released” inside our function instead of in our list of arguments:

def change_year(self, year_released=None): if year_released != self.year_released: self.year_released = year_released print("<> was released in <>.".format(self.name, self.year_released)) else: year_released = self.year_released print("This movie has not been changed.") print(year_released)

In this code, we set “year_released” to be equal to “self.year_released” if we do not specify a value for “year_released” in our function call.

Let’s create a new Movie object to test out our code:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

happy_gilmore = Movie("Happy Gilmore", 1995) happy_gilmore.change_year(1996)

We have incorrectly specified the year Happy Gilmore was released as 1995. We need to change it using the change_year() method. Our code returns:

Happy Gilmore was released in 1996. 1996

Our code was successfully executed. Let’s test our code to see what happens if the value of “year_released” is already equal to the one we specify in the change_year() method:

happy_gilmore = Movie("Happy Gilmore", 1996) happy_gilmore.change_year(1996)
This movie has not been changed. 1996

Our code executes the else statement in our code and then tells us that the movie has not been changed.

Conclusion

The “NameError: name ‘self’ is not defined” error is raised when you forget to specify “self” as a positional argument or when you use “self” in another argument in a list of arguments.

You solve this error by making sure that all methods in a function that use “self” include “self” in their list of arguments. If that does not work, make sure that no arguments in a list of arguments depend on “self” for their default values.

Now you’re ready to solve this Python error like a professional 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.

Источник

How to fix NameError: name ‘self’ is not defined

When working with Python classes and objects, you might encounter the following error:

This error occurs because Python can’t find the definition of the self variable that you called in your code.

There are two possible scenarios that cause this error:

  1. You use self as the default value for an argument
  2. You access self from a static method

This tutorial will show you how to fix the error in each scenario.

1. Using self as the default value for an argument

Suppose you have a class named Person with the following definition:

Next, you created a method named greet() inside the class defined as follows:
 After that, you created an instance of the class and called the greet() method:
You’ll get the following error:

This error occurs because the self.name attribute is used as the default argument for the name parameter.

In Python, default arguments are evaluated when Python runs the code for the first time. That is, when Python put your method definition in the memory and makes it available for calling.

But the self object is only available when the method is actually called. This is why you can’t use self as a default argument.

To resolve this error, you need to assign self to the parameter in your method body. A common pattern is to use None as the default argument, and change it inside the function as follows:

 Now you can run the greet() function without receiving the error:

But the drawback of this solution is that you can’t explicitly set the name parameter to None because it will just get reassigned to self.name .

If you have many parameters that use self attributes as the default arguments, then you need to create many if statements as shown above.

It looks ugly and inconvenient, but there’s no other way considering how Python evaluates the default arguments.

2. You access self from a static method

As you probably know, Python implicitly passed the self object as the first argument anytime you called a class method.

A static method is an exception to this rule because it was intended to work with class attributes instead of class instances.

Suppose you create a Person class with a static method called greet() as shown below:

 Next, you create a new instance of the class and call the greet() method as follows:

When you declared a method as static in Python, the self object is not passed implicitly, so the error occurs.

To resolve this error, you need to remove the @staticmethod modifier above the method name and define the self object as a parameter of the method:

 Now you can access self inside the greet() method without receiving the error.

Conclusion

The NameError: name ‘self’ is not defined occurs in Python when you try to access the self object from a place that doesn’t have the definition of self .

The most probable cause for this error is that you use the self attribute as the default argument of your method’s parameter, or you try to access self from a static method.

Keep in mind that this error doesn’t appear when you didn’t specify self as the first parameter of a method.

For that, you’ll get another error saying TypeError: method takes 0 positional arguments but 1 was given.

I hope this tutorial is helpful. Happy coding! 👍

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

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