Self in Python
If you have ever looked at a Python class and wondered why every method starts with a mysterious parameter called self, you are not alone. This is one of t...
Understanding the self Parameter in Python Classes
If you have ever looked at a Python class and wondered why every method starts with a mysterious parameter called self, you are not alone. This is one of the first things that confuses people coming from languages like Java or C++, where the equivalent is handled invisibly by the compiler.
In Python, self is simply a reference to the current instance of the class. When you call a method on an object, Python automatically passes that object as the first argument. By convention, this parameter is named self, but technically you could name it anything. The name self is just a widely followed agreement that keeps code readable and consistent.
class Counter: def __init__(self): self.count = 0
def increment(self): self.count += 1
def reset(self): self.count = 0
def value(self): return self.count
c = Counter() c.increment() c.increment() print(c.value()) # 2 c.reset() print(c.value()) # 0
When you call c.increment(), Python internally transforms this into Counter.increment(c). The object c is passed as self. Inside the method, self.count refers to the count attribute on that specific object. If you had two Counter objects, each would have its own count, and calling increment on one would not affect the other.
The self parameter is also why you access instance attributes with self.attribute rather than just attribute. Without self, Python would look for a local variable inside the method and not find the object's data. With self, you clearly indicate that you want to access or modify data that belongs to this particular instance.
Exam tip: Python does not enforce the name self. You will occasionally see code using other names like this or obj. However, using anything other than self is considered very bad practice and will confuse other developers. On exams, always use self and expect that any code sample using it follows the conventional behavior.