Python self Parameter
self is the reference to the current object that Python passes into every instance method, letting the method read and change that object's own data.
Every method defined in a class receives, as its first parameter, the object it was called on. By convention this parameter is named self. It is how a method knows which particular object it is working with when many objects share the same class. Without self, a method would have no way to reach the attributes that belong to that specific instance.
How self connects a call to an object
When you write obj.method(), Python automatically passes obj as self. That is why you define a method with self in its parameter list but never pass it explicitly at the call site. The two forms below are equivalent, and seeing them side by side makes the mechanism clear.
self is filled in automatically
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
c = Counter()
c.increment() # normal call, self = c
Counter.increment(c) # explicit form, same effect
print(c.count) # 2Using self to store and read data
Attributes attached to self live for as long as the object does, so one method can set a value that another method reads later. Each object keeps its own separate copy of these attributes.
Each object has its own self
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
small = Rectangle(2, 3)
big = Rectangle(10, 5)
print(small.area()) # 6
print(big.area()) # 50- self refers to the specific object a method is acting on.
- It is the first parameter of every instance method.
- Python passes it automatically when you call obj.method().
- Use self.attribute to store per-object data.