多态与鸭子输入有什么区别? [英] What is the difference between polymorphism and duck typing?

查看:65
本文介绍了多态与鸭子输入有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这两个术语有些困惑,这就是我所知道的:

I'm a little confused with the two terms, here's what I know:

多态性是通过公共接口处理不同类型的对象的能力.鸭式输入是一种动态类型,它允许不同类型的对象响应相同的方法.

Polymorphism is the ability of object of different types to be handled by a common interface. While duck typing, is a kind of dynamic typing that allows objects of different types to respond to the same methods.

据我了解,多态性更多地是关于创建一个可以在不同类之间共享的接口.鸭子类型是关于松散类型的,只要在消息的接收者上找到它,就可以调用方法.

From what I understand, polymorphism is more about creating an interface that can be shared across different classes. And duck typing is about loose typing that will allow methods to be called as long as it is found on the receiver of the message.

这是正确的吗?我对两者很困惑,它们似乎是相关的,但我不知道它们之间的关系.提前非常感谢!

Is this correct? I'm pretty confused on the two, they seem related but I do not know what their relationship is. Thanks a lot in advance!

推荐答案

多态(在面向对象编程的上下文中)意味着子类可以覆盖基类的方法.这意味着类的方法可以在子类中执行不同的操作.例如:类Animal可以具有方法talk(),而Animal的子类DogCat可以使方法talk()发出不同的声音.

Polymorphism (in the context of object-oriented programming) means a subclass can override a method of the base class. This means a method of a class can do different things in subclasses. For example: a class Animal can have a method talk() and the subclasses Dog and Cat of Animal can let the method talk() make different sounds.

鸭子输入意味着代码将只接受具有特定方法的任何对象.假设我们有以下代码:animal.quack().如果给定对象animal具有我们要调用的方法,那么我们就很好(不需要其他类型要求). animal实际上是Duck还是碰巧发出嘎嘎声的其他动物都没有关系.这就是为什么将其称为鸭子类型:如果它看起来像鸭子(例如,它有一个名为quack()的方法,那么我们可以像该对象是鸭子一样进行操作).

Duck typing means code will simply accept any object that has a particular method. Let's say we have the following code: animal.quack(). If the given object animal has the method we want to call then we're good (no additional type requirements needed). It does not matter whether animal is actually a Duck or a different animal which also happens to quack. That's why it is called duck typing: if it looks like a duck (e.g., it has a method called quack() then we can act as if that object is a duck).

那么这些有关系吗?它们只是编程语言可能具有的简单功能.有些编程语言具有多态性,但是没有鸭子类型(例如Java).也有具有多态性和鸭子类型的语言(例如Python).

So are these related? They are simply separate features that a programming language may have. There are programming languages which have polymorphism but that do not have duck typing (such as Java). There are also languages that have polymorphism and duck typing (such as Python).

这篇关于多态与鸭子输入有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆