DAY 10. 鸭子类型
这个概念来源于美国印第安纳州的诗人詹姆斯·惠特科姆·莱利(James Whitcomb Riley,1849-1916)的诗句:”When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.”
当我看到一只像鸭子一样走路,像鸭子一样游泳,像鸭子一样嘎嘎叫的鸟,我就叫它鸭子。
鸭子类型在动态编译语言如python,go中经常使用,意思是程序只关心对象行为而不关心对象类型,如
class Duck:def __init__(self, name):self._name = namedef call(self):print("gua gua gua")class Frog:def __init__(self, name):self._name = namedef call(self):print("gua gua gua")def quack(duck):duck.call()if __name__ == '__main__':duck = Duck('Duck')frog = Frog('Frog')quack(duck)quack(frog)
虽然duck和frog不是同一个类型,但他们都有相同的方法call,那就可以把他们“当作同一种类型——鸭子类型”