What is self in Python class methods, and why must it be written?
self is the first parameter of an instance method and receives the object the method was called on. Python passes it automatically; the name is only a convention.
Explain it simply
When a teacher calls "Rahul, stand up", the word Rahul tells the class which student the instruction is for. In Python, obj.method() is turned into Class.method(obj), so the method receives the object as its first argument. By convention that parameter is called self.
Java hides this and lets you write this only when needed. Python keeps it explicit, so attributes always need self. in front.
Example
class Counter:
def __init__(self):
self.count = 0 # attribute stored on this object
def hit(self):
self.count += 1
a = Counter()
b = Counter()
a.hit()
a.hit()
b.hit()
print(a.count, b.count) # 2 1
Counter.hit(b) # same as b.hit()
print(b.count) # 2Forgetting self in the definition gives TypeError: hit() takes 0 positional arguments but 1 was given.
What to say in the interview
"self is the instance the method is bound to. Python passes it implicitly as the first argument, so I must declare it in the signature and use self.attribute to reach instance data. The name is a convention, though everyone follows it."
Common mistakes
- Writing count = 0 inside __init__ and wondering why the attribute does not exist later.
- Leaving self out of the method signature.