Python NameError: name 'self' is not defined Solution

Posted in /  

Python NameError: name 'self' is not defined Solution

Vinay Khatri
Last updated on November 9, 2022

    The name "self" is the arbitrary name for the first argument value of every class method. When we call the method using the object, the value of the object is passed as the first parameter to the method itself. That's why the argument name is "self". The name "self" is conventional. We can name it as any valid identifier.

    If we have specified a different name to the self argument and used the self identifier inside the class method, we receive the error NameError: name 'self' is not defined .

    In this Python guide, we will discuss this error in detail and learn how to debug it. We will walk through the two most common scenarios where you may encounter this error in a Python program.

    Python Error: NameError: name 'self' is not defined

    The "self" is the conventional first argument name that is specified while defining a function or method for a class. While calling the method using an object, Python passes the object as the value to the self-argument.

    Example

    class Car:
        def __init__(self, car_name, owner):
            self.car_name = car_name
            self.owner = owner
        
        def show_detail(self):
            print("Car Name:", self.car_name)
            print("Car Owner:", self.owner)
    
    # create car object
    car1= Car("Honda Civic", 'Joe Smith')
    
    # call the function
    car1.show_detail()

    Output

    Car Name: Honda Civic
    Car Owner: Joe Smith

    In this example, the method show_detail(self) has an argument self. But when we call the method using the  object joe, there we did not specify any argument joe.show_detail() , this is because when we call a method using an object, there we do not need to specify the value for self argument.

    In this example, the value joe will act as the first argument value self to the method. Now let's discuss the two common example scenario where we can encounter the error "NameError: name 'self' is not defined"

    Common Error Example Scenario

    1. Misspelled the name self
    2. calling the self-value in the arguments.

    1. Misspelled the name self

    If we misspell the name self while defining the arguments for the method, and using the name self inside the method, there we will receive the error.

    Example

    class Car:
        def __init__(self, car_name, owner):
            self.car_name = car_name
            self.owner = owner
        
        #missplet the name self
        def show_detail(slf):
            print("Car Name:", self.car_name)
            print("Car Owner:", self.owner) 
    
    # create car object
    car1 = Car("Honda Civic", 'Joe Smith')
    
    # call the function
    car1.show_detail()

    Output

    Traceback (most recent call last):
      File "main.py", line 15, in 
        car1.show_detail()
      File "main.py", line 8, in show_detail
        print("Car Name:", self.car_name)
    NameError: name 'self' is not defined

    In the above example, we are receiving an error in the show_detail(slf) method. Inside the method, we are trying to access the car_name property using the self name. But in the method definition, we have misspelled the name with slf .

    Solution: To solve the above problem, we need to ensure that we are specifying the correct self name while defining the function.

    class Car:
        def __init__(self, car_name, owner):
            self.car_name = car_name
            self.owner = owner
        
        def show_detail(self):
            print("Car Name:", self.car_name)
            print("Car Owner:", self.owner) 
    
    # create car object
    car1 = Car("Honda Civic", 'Joe Smith')
    
    # call the function
    car1.show_detail()

    Output

    Car Name: Honda Civic
    Car Owner: Joe Smith

    2. calling the self-value in the arguments

    The value of self is passed to the method when we call the method using the object. If we try to pass the self as the default argument value there, also we will receive the error NameError: name 'self' is not defined .

    Example

    class Car:
        def __init__(self, car_name, owner):
            self.car_name = car_name
            self.owner = owner
        
        def show_detail(self):
            print("Car Name:", self.car_name)
            print("Car Owner:", self.owner) 
        
        # evaluating self at function definition
        def change_owner(self, name= self.owner):
            self.owner = name
    
    # create car object
    car1 = Car("Honda Civic", 'Joe Smith')
    
    # change owner
    car1.change_owner("Jose")
    
    car1.show_detail()

    Output

    Traceback (most recent call last):
      File "main.py", line 1, in 
        class Car:
      File "main.py", line 11, in Car
        def change_owner(self, name= self.owner):
    NameError: name 'self' is not defined

    In this example, we are receiving the error with def change_owner(self, name= self.owner): . While defining the method change_owner() we have provided a default value to the name argument self.owner .

    Python evaluates a function's or method's default arguments during the definition. And the value of self is only assigned during the method calls. That's why in the method definition, Python could not evaluate the value of self.owner and raise the error.

    Solution

    We can not use self as a default parameter. To solve the above problem, we will give the name a value of None as a default argument, that will make the name as an optional argument.

    class Car:
        def __init__(self, car_name, owner):
            self.car_name = car_name
            self.owner = owner
        
        def show_detail(self):
            print("Car Name:", self.car_name)
            print("Car Owner:", self.owner) 
        
        def change_owner(self, name= None):
            if name==None:
                self.owner=self.owner
            else:
                self.owner = name 
            
    
    # create car object
    car1 = Car("Honda Civic", 'Joe Smith')
    
    # change owner
    car1.change_owner("Jose")
    
    car1.show_detail()

    Output

    Car Name: Honda Civic
    Car Owner: Jose

    Conclusion

    The Error statement " NameError: name 'self' is not defined ", is one of the most common errors that many Python learners commit while dealing with class, method, and objects. The error statement has two sub-statements NameError, and "name 'self' is not defined".

    The NameError is a Python exception type that raises in a program when Python is not able to find the identifier name in its scope. The statement " name 'self' is not defined " is the error message that raises along with the NameError when we use the name self that is not defined for a method, program, and default argument.

    If you are still getting this error in your Python program, please share your code and query in the comment section.

    People are also reading:

    Leave a Comment on this Post

    0 Comments