When you call a method through an instance, Python automatically passes that instance as the first argument to the method, bound to whatever name is listed first in the method's parameter list — self is purely a naming convention, not a keyword, but virtually every Python codebase follows it. Inside the method, self is how you access that specific instance's attributes and call its other methods, which is why assigning to a self attribute in one method makes that value visible to every other method called on the same instance.
1Understanding self Parameter
When you call a method through an instance, Python automatically passes that instance as the first argument to the method, bound to whatever name is listed first in the method's parameter list — self is purely a naming convention, not a keyword, but virtually every Python codebase follows it. Inside the method, self is how you access that specific instance's attributes and call its other methods, which is why assigning to a self attribute in one method makes that value visible to every other method called on the same instance.
Forgetting self as the first parameter in a method definition, or forgetting to write self. before an attribute you meant to access, are two of the most common mistakes for people newer to Python's OOP model — both usually surface as a confusing TypeError or AttributeError.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
r = Rectangle(4, 5)
print(r.area())2Practical Example
Here is a real-world application of self Parameter showing how it is used in production Python code.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
r = Rectangle(4, 5)
print(Rectangle.area(r))3Best Practices
Follow these guidelines when working with self Parameter:
1. Always name the first parameter of an instance method self, even though Python doesn't enforce the name, since every reader expects it
2. Access instance attributes and other methods through self inside instance methods, rather than trying to reference bare variable names
3. Remember self is passed automatically by Python when calling a method through an instance — you don't pass it explicitly at the call site
Tip: Forgetting self as the first parameter in a method definition, or forgetting to write self. before an attribute you meant to access, are two of the most common mistakes for people newer to Python's OOP model — both usually surface as a confusing TypeError or AttributeError.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
r = Rectangle(4, 5)
print(r.area())