ErrorOracle
python

NameError: name 'self' is not defined

Error message

NameError: name 'self' is not defined

What broke

'self' is a reference to the instance of a class in Python, and it must be used within class methods. If you try to use 'self' in a function that is not defined as a method of a class, Python will raise a NameError.

Why it broke

This error typically happens when you mistakenly reference 'self' in a standalone function or outside of any class context. Since 'self' is not defined in such scopes, Python cannot recognize it.

How to fix

To fix this error, ensure that 'self' is only used within class methods. If you need to use a variable in a standalone function, define it without 'self'.

Code fix

class MyClass:
    def my_method(self):
        print('Hello, World!')

Explained by ErrorOracle

Prevention tip

If you need to use a variable in a standalone function, define it without 'self'.

Was this helpful?

AI-generated explanation. Always verify fixes in your codebase.