![]()
In Python, the error message:
NameError: name 'self' is not defined
occurs when you try to use self inside a class method, but Python does not recognize it.
This usually happens in object-oriented programming (OOP) when defining class methods incorrectly.
1. What Does the Error Mean?
Python uses self as a reference to the instance of a class. It must be explicitly included as the first parameter in instance methods.
If self is missing or incorrectly used, Python does not know what self refers to, leading to this error.
Example of the Error:
class MyClass:
def say_hello():
print("Hello, World!")
print(self) # Trying to use 'self' without defining it
obj = MyClass()
obj.say_hello()
Error Output:
NameError: name 'self' is not defined
Why?
- The method
say_hello()does not haveselfas its first parameter. - When calling
obj.say_hello(), Python expectsself, but it is missing.
2. Causes and Solutions
Cause 1: Missing self in Instance Methods
When defining a class method, self must be the first parameter.
Incorrect Code:
class Car:
def start_engine(): # 'self' is missing
print("Engine started!")
my_car = Car()
my_car.start_engine() # Error
Error Output:
TypeError: start_engine() takes 0 positional arguments but 1 was given
Solution: Add self as the First Parameter
class Car:
def start_engine(self): # Correct: 'self' is included
print("Engine started!")
my_car = Car()
my_car.start_engine() # No error
Cause 2: Using self Outside of a Method
If you use self outside of an instance method, Python does not recognize it.
Incorrect Code:
class Animal:
print(self) # Error: 'self' is not defined
dog = Animal()
Error Output:
NameError: name 'self' is not defined
Why?
selfonly exists inside instance methods.
Solution: Use self Inside a Method
class Animal:
def show_self(self):
print(self) # Now 'self' is valid
dog = Animal()
dog.show_self()
Cause 3: Incorrect Use of self in __init__
If self is not passed in __init__(), the instance variables won’t be set.
Incorrect Code:
class Person:
def __init__(name, age): # 'self' is missing
self.name = name # Error
self.age = age
p = Person("John", 30)
Error Output:
NameError: name 'self' is not defined
Solution: Add self as the First Parameter
class Person:
def __init__(self, name, age): # Corrected
self.name = name
self.age = age
p = Person("John", 30)
print(p.name, p.age) # Output: John 30
Cause 4: Calling a Method Without an Instance
Trying to call an instance method directly from a class without an instance can cause this error.
Incorrect Code:
class Computer:
def display_specs(self):
print("16GB RAM, i7 Processor")
Computer.display_specs() # Calling without an instance
Error Output:
TypeError: display_specs() missing 1 required positional argument: 'self'
Solution: Create an Instance Before Calling
comp = Computer()
comp.display_specs() # No error
Cause 5: Using self in a Static Method
Static methods do not receive self automatically.
Incorrect Code:
class MathOperations:
@staticmethod
def add(a, b):
return self.a + self.b # 'self' is invalid here
print(MathOperations.add(3, 4))
Error Output:
NameError: name 'self' is not defined
Why?
- Static methods do not receive
selfbecause they are independent of class instances.
Solution: Remove self in Static Methods
class MathOperations:
@staticmethod
def add(a, b): # No 'self' here
return a + b # Corrected
print(MathOperations.add(3, 4)) # Output: 7
Cause 6: Using self in a Class Method Without cls
Class methods should use cls, not self.
Incorrect Code:
class Library:
books = 100
@classmethod
def show_books(self): # Wrong: Use 'cls' instead of 'self'
print(f"Total books: {self.books}")
Library.show_books()
Error Output:
AttributeError: type object 'Library' has no attribute 'books'
Solution: Use cls Instead of self
class Library:
books = 100
@classmethod
def show_books(cls): # Corrected
print(f"Total books: {cls.books}")
Library.show_books() # Output: Total books: 100
3. Best Practices to Avoid This Error
To prevent "NameError: name 'self' is not defined", follow these best practices:
Always Include self in Instance Methods
class Example:
def my_method(self):
print("Method called")
Use cls for Class Methods
class Example:
@classmethod
def class_method(cls):
print("Class method")
Use self Only Inside Instance Methods
class Example:
def __init__(self, value):
self.value = value # Correct
def show(self):
print(self.value)
Use Static Methods When self Is Not Needed
class Example:
@staticmethod
def static_method():
print("Static method")
Create Instances Before Calling Instance Methods
obj = Example()
obj.my_method() # No error
