Nameerror: name self is not defined in Python
Last Updated :
28 Apr, 2025
Python, a dynamically typed and object-oriented programming language, is lauded for its simplicity and readability. However, even the most seasoned developers can encounter stumbling blocks, and one such common hurdle is the "NameError: name 'self' is not defined." In this article, we will see how to fix Nameerror: Name 'self' is not defined in Python.
What is Nameerror: Name 'self' Is Not Defined In Python?
The 'NameError: name 'self' is not defined' typically arises in the context of object-oriented programming (OOP) when working with classes and instances. 'self' is a convention in Python used to refer to the instance of a class, and encountering this error indicates that the interpreter cannot recognize the intended reference to the instance. Understanding the scenarios in which this error occurs is pivotal for devising effective solutions.
Why does Undefined Variable NameError Occurs in Python
Below are some reasons due to which Nameerror: Name 'self' Is Not Defined Occurs in Python:
- Missing self in Method Declaration
- Incorrect Spelling of 'self'
- Accessing Instance Variables Without 'self'
- Incorrect Capitalization of 'self'
Missing self in Method Declaration
In this example, 'self' is absent from the my_method declaration, causing a NameError when attempting to access instance attributes within the method.
Python3
class MyClass:
def my_method(n):
self.n=n
print("Hello, World!")
obj = MyClass()
obj.my_method()
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 7, in <module>
obj.my_method()
File "Solution.py", line 3, in my_method
self.n=n
NameError: name 'self' is not defined
Incorrect Spelling of 'self'
A common typographical error, such as misspelling 'self' as 'Slef,' can lead to a NameError as the interpreter fails to recognize the intended reference.
Python3
class AnotherClass:
def __init__(Slef, value):
self.value = value
obj = AnotherClass(42)
print(obj.value)
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 5, in <module>
obj = AnotherClass(42)
File "Solution.py", line 3, in __init__
self.value = value
NameError: name 'self' is not defined
Accessing Instance Variables Without 'self'
Forgetting to use 'self.' when assigning values to instance variables within the constructor can result in the 'self' variable being undefined.
Python3
class YetAnotherClass:
def __init__(s,name):
self.name = name
obj = YetAnotherClass("John")
print(obj.name)
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 5, in <module>
obj = YetAnotherClass("John")
File "Solution.py", line 3, in __init__
self.name = name
NameError: name 'self' is not defined
Incorrect Capitalization of 'self'
Python is case-sensitive, and using 'Self' instead of 'self' in the method signature will lead to a NameError.
Python3
class CapitalizedClass:
def __init__(Self, value): # Incorrect capitalization of 'self'
self.value = value
obj = CapitalizedClass(10)
print(obj.value)
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 5, in <module>
obj = CapitalizedClass(10)
File "Solution.py", line 3, in __init__
self.value = value
NameError: name 'self' is not defined
Fix Nameerror: Name self' Is Not Defined in Python
Below are some solution approaches to solve Nameerror: Name 'self' Is Not Defined error in Python:
- Method Declaration
- Spelling Check
- Instance Variable Assignments
- Capitalization Check
Python Method Declaration
In this example, the 'self' parameter is added to the method declaration of my_method in the MyClass class, ensuring proper referencing of instance attributes within the method.
Python3
class MyClass:
def my_method(self,n):
self.n=n
print("Hello, World!")
obj = MyClass()
obj.my_method(6)
Spelling Check in Class Constructor
In this example, the spelling error 'Slef' is corrected to 'self' in the constructor of the AnotherClass class, allowing for the proper creation and manipulation of instances.
Python3
class AnotherClass:
def __init__(self, value):
self.value = value
obj = AnotherClass(42)
print(obj.value)
Instance Variable Assignments
In this example, the missing 'self.' is added before variable assignment in the constructor of the YetAnotherClass class, ensuring that the variable belongs to the instance.
Python3
class YetAnotherClass:
def __init__(self,name):
self.name = name
obj = YetAnotherClass("John")
print(obj.name)
Capitalization Check
In this example, the incorrect capitalization 'Self' is corrected to 'self' in the constructor of the CapitalizedClass class, resolving the NameError and allowing proper instantiation.
Python3
class CapitalizedClass:
def __init__(self, value):
self.value = value
obj = CapitalizedClass(10)
print(obj.value)
Similar Reads
Nameerror: Name '__File__' Is Not Defined" in Python One common issue that developers encounter is the "NameError: name 'file' is not defined." This error typically occurs when trying to access the __file__ attribute in a context where it is not recognized. In this article, we'll explore what this error means and discuss three scenarios where it might
4 min read
How to Fix "NameError: name 'os' is not defined" in Python If we are working with Python and encounter an error that says "NameError: name 'os' is not defined", then we need not worry, it is a very common issue, and fixing this error is very simple. This error usually occurs when we try to use the os module without importing it first. In this article, we wi
3 min read
How to Fix: NameError name âpdâ is not defined In this article we will discuss how to fix NameError pd is not defined in Python. When we imported pandas module without alias and used pd in the code, the error comes up. Example: Code to depict error Python3 # import pandas module import pandas # create dataframe data = pd.DataFrame({'a': [1, 2],
2 min read
How to Fix: NameError name ânpâ is not defined In this article, we will discuss how to fix NameError np that is not defined in Python. When we imported the NumPy module without alias and used np in the code, the error comes up. Example: Code to depict error Python3 # import numpymodule import numpy # create numpy array a = np.array([1, 2, 3, 45]
2 min read
Handling NameError Exception in Python Prerequisites: Python Exception HandlingThere are several standard exceptions in Python and NameError is one among them. NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are :1. Misspelled built-in functions
2 min read
Python IMDbPY â Getting Person name from searched name In this article we will see how we can get the person name from the searched list of name, we use search_name method to find all the related names.search_name method returns list and each element of list work as a dictionary i.e. they can be queried by giving the key of the data, here key will be na
2 min read