self Keyword
Referencing the instance
Interview Relevant: Python-specific
self Keyword
Reference to the current instance.
Code Examples
Understanding self in Python.
python
1class Counter:
2 def __init__(self):
3 self.count = 0
4
5 def increment(self):
6 self.count += 1
7 return self # Return self for chaining
8
9 def reset(self):
10 self.count = 0
11 return self
12
13# Method chaining
14c = Counter()
15c.increment().increment().increment()
16print(c.count) # 3
17
18# self is just convention (can use any name)
19class Example:
20 def method(this): # Works but don't do this!
21 return this
22
23# self is passed automatically
24c.increment() # Python passes c as self
25Counter.increment(c) # Equivalent explicit call