22
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

`return self`でメソッドチェーン

Last updated at Posted at 2013-11-04

オープンソースを読んでいたらreturn selfしているメソッドがあって、これをやると何が起きるのか知らなかったのでメモ。

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

結果

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'

クラスのメソッドでreturn selfをしないCar2のインスタンスででメソッドチェーンをやろうとするとエラーが起きる。
return selfをやるとメソッドチェーンができるようになる。
car1なら何回fill()drive()をつなげても良い。

参考

22
20
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?