How to Resolve "NameError: name 'self' is not defined" in Python Classes
The NameError: name 'self' is not defined error is a common issue in Python, particularly when working with classes and methods. This error arises when self is used incorrectly or in contexts where it's not available.
This guide explains the causes of this error and provides clear, concise solutions, along with best practices.
Understanding self and the Error
In Python classes, self is a reference to the current instance of the class. It's used within methods to access and modify the object's attributes (instance variables).
selfis implicitly passed as the first argument to instance methods when you call them on an object.- It's not available outside of methods or as a default argument value during class definition.
Common Causes and Solutions
Using self as a Default Argument (Incorrect)
The most common cause of the NameError is trying to use self as a default argument value within a method's definition:
class Employee():
def __init__(self, first, last=self.first): # ⛔️ ERROR! self is not defined here
self.first = first
self.last = last
# ⛔️ NameError: name 'self' is not defined
# tom = Employee('tom', 'nolan')
Why this happens: Default argument values are evaluated when the function is defined, not when it's called. At the time of definition, the instance (self) doesn't exist yet.
Solution: Use None as the default value and set the attribute inside the method:
class Employee():
def __init__(self, first, last=None):
self.first = first
if last is None:
self.last = self.first # Assign self.first if last is not provided
else:
self.last = last
tom = Employee('tom')
print(tom.first) # Output: tom
print(tom.last) # Output: tom
alice = Employee('alice', 'smith')
print(alice.first) # Output: alice
print(alice.last) # Output: smith
Using self Outside of Methods (Incorrect)
You can not use self directly within the class body, outside of any method definition:
class Employee():
# ⛔️ NameError: name 'self' is not defined
#self.salary = 123 # This is incorrect
def __init__(self, first, last):
self.first = first
self.last = last
self.salary = 123 # This is the correct place.
tom = Employee('tom', 'nolan') # Correct instantiation
print(tom.salary) # Output: 123
Why this happens: self only exists within the context of a method call on an instance of the class. Outside of a method, there's no instance, so self is undefined.
Solution:
-
Instance Variables: If
salaryis meant to be an instance variable (unique to eachEmployeeobject), initialize it inside the__init__method (or another instance method). That's whereselfis valid. -
Class Variables: To define attributes shared between all instances of the class use class variables. If
salaryshould be a class variable (shared by allEmployeeinstances), define it directly in the class body withoutself:class Employee():
default_salary = 123 # This is a CLASS variable
def __init__(self, first, last):
self.first = first
self.last = last
alice = Employee('alice', 'smith')
tom = Employee('tom', 'nolan')
print(alice.default_salary) # Output: 123
print(tom.default_salary) # Output: 123
Forgetting self as a Method Parameter
If you define a method that uses instance attributes (or calls other instance methods) but forget to include self as the first parameter, you'll also get a NameError:
class Employee():
def __init__(self, first, last):
self.first = first
self.last = last
# Missing self parameter
def greet(self, greet_str):
return greet_str + self.first + ' ' + self.last
Solution: Always include self as the first parameter of instance methods:
class Employee():
default_salary = 123
def __init__(self, first, last):
self.first = first
self.last = last
def greet(self, greet_str): # Corrected Method
return greet_str + self.first + ' ' + self.last
alice = Employee('alice', 'smith')
tom = Employee('tom', 'nolan')
print(alice.greet('hi ')) # Output: hi alice smith
print(tom.greet('hey ')) # Output: hey tom nolan
print(alice.default_salary) # Output: 123
print(tom.default_salary) # Output: 123
- Remember that
selfshould always be the first parameter of instance methods.
Conclusion
The NameError: name 'self' is not defined in Python classes stems from misusing the self reference.
selfrepresents the instance and is only valid within instance methods.- Avoid using
selfas a default argument or outside of methods. - Always include
selfas the first parameter of instance methods.
By understanding these rules, you'll avoid this common error and write correct, object-oriented Python code.