Object-Oriented Programming
self Keyword
Understanding instance reference and method binding
Interview: Tests deep understanding of Python object model — method binding, unbound methods, and explicit self passing
The self keyword is a reference to the current instance of a class. It's the first parameter of every instance method and is automatically passed by Python. Unlike languages like Java or C++, Python makes self explicit — you must include it in method definitions and use it to access instance attributes.
Why Explicit self?
- Explicit is better than implicit — Python's philosophy
- Makes it clear whether you're accessing instance or local variables
- Allows calling methods on other objects easily
- Enables powerful patterns like method binding and monkey patching
Method Binding
When you access obj.method, Python creates a bound method — a callable that automatically passes obj as self. You can also call unbound methods explicitly: Class.method(obj).
Method Chaining
By returning self from methods, you enable fluent interface patterns like obj.a().b().c(). This is common in builder patterns, configuration APIs, and query builders.
Common Pitfall
While self is just a convention (you could name it this or anything), never use a different name. All Python code, tools, and linters expect self.
Use Cases
Method chaining for fluent interfaces (query builders, configuration)
Builder pattern for constructing complex objects step by step
Explicit self passing for metaprogramming and dynamic method dispatch
Bound methods for callbacks and event handlers
Accessing instance state in methods for object behavior
Common Mistakes
Forgetting self parameter in method definition — causes TypeError
Using a name other than self (technically works but violates convention)
Not returning self when method chaining is expected
Confusing bound methods (obj.method) with function objects (Class.method)
Trying to access self in @staticmethod (not available — use @classmethod or instance method)