Why would you return self from a class method?
Experience Level: Junior
Tags: Python
Answer
Returning self allows you to define a fluent interface that can then be called in a chain. So instead of calling class.do_something() and class.do_something_else(), you call class.do_something().do_something_else()
This is great for example in conjunction with the Builder pattern.
Example:
class MyClass:
def do_something(self):
return self
def do_something_else(self):
return self
value = MyClass() \
.do_something() \
.do_something_else()
Related Python job interview questions
How do you create a set with 3 values in Python?
Python JuniorWhat is a decorator in Python?
Python JuniorHow do you detect if the optional parameter value was set?
Python JuniorHow do you define an optional parameter with no value in Python?
Python JuniorHow do you define an optional parameter with a default value in Python?
Python Junior