Python
NameError
self
debugging
error-handling

NameError name 'self' is not defined

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

NameError: name 'self' is not defined usually appears when instance method syntax is mixed with function level code in Python. The fix is simple once you understand that self is just a conventional first parameter name passed automatically for instance methods. Most cases come from indentation or method signature mistakes.

Why the Error Happens

Inside a class, methods that operate on instance data must include self as first parameter. If missing, any reference to self in method body raises NameError.

Incorrect example:

python
class User:
    def set_name(name):
        self.name = name

Correct version:

python
class User:
    def set_name(self, name):
        self.name = name

Now Python passes instance object automatically when method is called.

Common Places This Error Appears

One common case is code placed outside class block but still referencing self.

python
1class Counter:
2    def __init__(self):
3        self.value = 0
4
5# Wrong scope
6self.value += 1

Another case is static method confusion. Static methods do not receive instance automatically.

python
1class MathTools:
2    @staticmethod
3    def double(x):
4        return x * 2

Inside a static method, using self is invalid unless you pass an instance manually.

Debugging Checklist

When this error appears, inspect three things quickly:

  1. Method signature includes self for instance methods.
  2. Indentation keeps code inside correct class and method blocks.
  3. Decorator choice matches intended behavior, instance, class, or static method.

A small reproducible test speeds diagnosis.

python
1class Person:
2    def __init__(self, name):
3        self.name = name
4
5    def greet(self):
6        return f"Hello {self.name}"
7
8p = Person("Ana")
9print(p.greet())

If this pattern works, compare it against failing code structure.

@classmethod receives class object as cls, not self.

python
1class Config:
2    version = "1.0"
3
4    @classmethod
5    def get_version(cls):
6        return cls.version

Mixing self and cls incorrectly can produce similar confusion and hard to read APIs.

Refactor Patterns That Prevent self Errors

Using consistent class patterns reduces this error class across a codebase. Keep constructors, instance methods, and static utilities visually distinct.

python
1class InvoiceService:
2    def __init__(self, tax_rate):
3        self.tax_rate = tax_rate
4
5    def total_with_tax(self, amount):
6        return amount * (1 + self.tax_rate)
7
8    @staticmethod
9    def validate_amount(amount):
10        return amount >= 0

In this pattern, any method using instance state must include self, while utility logic that does not need instance data stays static.

Tooling Checks

Linters and type checkers catch many self mistakes early. Running tooling in pre commit hooks prevents broken method signatures from reaching shared branches.

bash
python -m pip install ruff mypy
ruff check .
mypy .

Use automated checks along with small unit tests for class APIs.

python
def test_total_with_tax():
    svc = InvoiceService(0.1)
    assert svc.total_with_tax(100) == 110

Early feedback from lint and tests is faster than debugging runtime NameError in production logs.

Common Pitfalls

  • Omitting self in instance method signatures.
  • Referencing self in module level code outside class context.
  • Using wrong decorator for method intent.
  • Copy pasting code blocks with broken indentation.
  • Treating self as reserved keyword instead of regular parameter name.

Summary

  • self must be declared in instance method signatures.
  • Scope and indentation errors are frequent root causes.
  • Use @staticmethod and @classmethod only for matching method semantics.
  • Build minimal reproducible examples to isolate the issue quickly.
  • Consistent class structure prevents most self related errors.
  • Review class methods during code review with a quick signature scan to ensure instance methods declare self and class methods use cls consistently.
  • Keep method responsibilities narrow so indentation and scope remain obvious and accidental references to undefined instance context become less likely.
  • Prefer explicit class templates in scaffolding tools so new modules start with correct method signatures and reduce repetitive human mistakes.
  • Consistent editor snippets can eliminate many signature related defects before they are committed.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.