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

Chat

Oh, the operator is not available. Leave us your comments. We will answer all your questions as soon as possible.

Comments

Anonymous
Καλησπέρα.
Anonymous
the infinteis -3/15 so 1triition / infinet
Anonymous
e
Anonymous
<a href="https://inspirum.pl "
Anonymous
[url]https://inspirum.pl[/url]
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e