[PYTHON] Method chain with `return self`

When I was reading open source, there was a method that was return self, and I didn't know what would happen if I did this, so make a note.

class Car1(object):
    def __init__(self):
        self.miles = 0
        self.gas = 0

    def drive(self, d):
        self.miles += d
        self.gas -= d
        return self

    def fill(self, g):
        self.gas += g
        return self


class Car2(object):
    def __init__(self):
        self.miles = 0
        self.gas = 0

    def drive(self, d):
        self.miles += d
        self.gas -= d

    def fill(self, g):
        self.gas += g


if __name__ == '__main__':
    car1 = Car1()
    car1.fill(100).drive(50)

    print 'car1 miles', car1.miles
    print 'car1 gas', car1.gas

    car2 = Car2()
    car2.fill(100).drive(50)

    print 'car2 miles', car2.miles
    print 'car2 gas', car2.gas

result

car1 miles 50
car1 gas 50
Traceback (most recent call last):
File "chain.py", line 38, in <module>
car2.fill(100).drive(50)
AttributeError: 'NoneType' object has no attribute 'drive'

Don't do return self in class methods I get an error when trying to do a method chain on an instance of Car2. If you do return self, you will be able to create a method chain. With car1, you can connectfill ()anddrive ()as many times as you like.

reference

Recommended Posts

Method chain with `return self`
How to return multiple indexes with index method
[Python] Calculation method with numpy
Graph drawing method with matplotlib
Implement method chain in Python
Be careful with easy method references
Be careful with Python's append method
return errdetails on error with grpc-node
Implemented inter-frame difference method with OpenCV