Last modified: Feb 23, 2025 By Alexander Williams

Fix Python NameError: Name 'self' Not Defined

Encountering a NameError: name 'self' is not defined in Python can be confusing for beginners. This error typically occurs when the self keyword is used incorrectly in classes or methods. Let's explore why this happens and how to fix it.

What Causes the 'self' NameError?

The self keyword in Python refers to the instance of a class. It is used to access class attributes and methods. The error arises when self is used outside a class or in a context where it is not recognized.

For example, if you mistakenly use self in a standalone function or forget to include it as the first parameter in a class method, Python will raise this error.

Common Scenarios and Fixes

Here are some common scenarios where this error occurs and how to resolve them:

1. Using 'self' Outside a Class

If you use self outside a class, Python won't recognize it. For example:


    def my_function():
        print(self.name)  # Error: 'self' is not defined
    

To fix this, ensure self is only used within class methods. If you need to access instance attributes, define the function inside a class.

2. Forgetting 'self' in Method Definition

When defining a method in a class, self must be the first parameter. Forgetting it will cause the error:


    class MyClass:
        def print_name():  # Missing 'self'
            print(self.name)  # Error: 'self' is not defined
    

To fix this, add self as the first parameter:


    class MyClass:
        def print_name(self):  # Correct
            print(self.name)
    

3. Incorrectly Using 'self' in Static Methods

Static methods do not require self. Using it in a static method will cause the error:


    class MyClass:
        @staticmethod
        def print_name(self):  # Incorrect
            print(self.name)  # Error: 'self' is not defined
    

To fix this, remove self from the static method definition:


    class MyClass:
        @staticmethod
        def print_name():  # Correct
            print("Name")
    

Example Code and Output

Here’s a complete example demonstrating the correct use of self:


    class MyClass:
        def __init__(self, name):
            self.name = name

        def print_name(self):
            print(self.name)

    obj = MyClass("Python")
    obj.print_name()  # Output: Python
    

    Output: Python
    

Conclusion

The NameError: name 'self' is not defined is a common issue for Python beginners. It occurs when self is used incorrectly or outside a class context. By ensuring self is used properly in class methods and avoiding it in static methods, you can easily fix this error.

For more tips on handling Python errors, check out our guide on How to Fix NameError in Python.