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()

Python for beginners
Python for beginners

Are you learning Python ? Try our test we designed to help you progress faster.

Test yourself