Python – Purpose of `return self` from a class method

method-chainingpython

I came across something like this in an open-source project. Methods that modify instance attributes return a reference to the instance. What is the purpose of this construct?

class Foo(object):

  def __init__(self):
    self.myattr = 0

  def bar(self):
    self.myattr += 1
    return self

Best Answer

It's to allow chaining.

For example:

var Car = function () {
    return {
        gas : 0,
        miles : 0,
        drive : function (d) {
            this.miles += d;
            this.gas -= d;
            return this;
        },
        fill : function (g) {
            this.gas += g;
            return this;
        },
    };
}

Now you can say:

var c = Car();
c.fill(100).drive(50);
c.miles => 50;
c.gas => 50;
Related Topic