duck type

作者: grimlock44 | 来源:发表于2018-09-20 15:35 被阅读0次

duck typing
俚语:如果一个东西像鸭子一样走路和呱呱叫,那么它一定是鸭子

计算机领域中,duck typing相对应的是normal typing(对象的类型决定了对象的特性),duck typing中对象的类型不重要,只要对象有类型A的方法和属性,那么它被当做类型A来使用。熟悉c的同学应该明白c就是normal typing,在编译阶段静态检查,函数定义和传参类型不一致就报错。对应的python属于duck typing,基本上是类型随便混用,没有静态检查类型匹配情况,只有运行起来找不到相应属性和方法时才报错。

python的例子:任何类型的对象可以用在任何上下文中,只有方法找不到了才报错
class Duck:
def fly(self):
print("Duck flying")

class Airplane:
def fly(self):
print("Airplane flying")

class Whale:
def swim(self):
print("Whale swimming")

def lift_off(entity):
entity.fly()

duck = Duck()
airplane = Airplane()
whale = Whale()

lift_off(duck) # prints Duck flying 有fly方法就能用 不关心类型是什么
lift_off(airplane) # prints Airplane flying 有fly方法就能用 不关心类型是什么
lift_off(whale) # Throws the error 'Whale' object has no attribute 'fly' 异常是因为没有fly方法 而不是因为类型不对

相关文章

  • duck type

    duck typing俚语:如果一个东西像鸭子一样走路和呱呱叫,那么它一定是鸭子 计算机领域中,duck typi...

  • Duck Type 鸭子类型

    Duck Typing is a [type system] used in dynamic languages....

  • go笔记

    0.关键词:ok parttern ,type switch, duck typing, structural...

  • 餐饮费用

    8月12日 Duck and Waffle: 1、Duck and Waffle 18英镑 2、Duck Egg ...

  • mock in iOS

    博客链接 在面向对象编程中,有个非常有趣的概念叫做duck type,意思是如果有一个走路像鸭子、游泳像鸭子,叫声...

  • 周黑鸭

    Zhou Black Duck is dedicated to promoting Zhou Black Duck...

  • NiteNite

    NiteNite, little duck.. Sleep tight! ∵ The little duck wa...

  • 英文食谱01--啤酒鸭

    Beer Braised Duck Ingredients: 1.a can of beer 2.a duck (...

  • _duck

    英文版:https://t.co/cmXB2Clj8D中文版:http://v.qq.com/page/n/u/a...

  • Strategy模式:橡皮鸭子不会飞

    需求故事 作为黄鸭子,我希望可以display “Yellow Duck”,可以fly "Yellow Duck ...

网友评论

      本文标题:duck type

      本文链接:https://www.haomeiwen.com/subject/vilnnftx.html