为什么会有return self 的写法

175 阅读1分钟

当然是通过返回对象本身以便进行后续调用。最常见的就是链式调用. Returning self from a method simply means that your method returns a reference to the instance object on which it was called. This can sometimes be seen in use with object oriented APIs that are designed as a fluent interface that encourages method cascading. 例子如下:

class Pig(object):

  def __init__(self):
    self.ball = 0

  def eat(self):
    self.ball += 1
    return self

f = Pig()
f.eat().eat().eat()
print(f.myattr)