方法链
python原创方法链小于 1 分钟约 178 字
前言
方法链是指一个对象一次调用其自身的多个方法,通常写作对象.方法1.方法2。由于这种调用方法看起来像一个链条,所以我们将其称作方法链。通过方法链我们可以简化代码。
实例
class Animal():
def eat(self):
print("The animal is eating")
return self
def sleep(self):
print("The animal is sleeping")
return self
def run(self):
print("The animal is running")
return self
此时我们再对类进行实例化,就能调用其多个方法了:
调用
animal = Animal()
animal.eat().sleep().run()
>>> The animal is eating
>>> The animal is sleeping
>>> The animal is running