多态性和鸭子类型有什么区别? [英] What is the difference between polymorphism and duck typing?

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

问题描述

我对这两个术语有点困惑,以下是我所知道的:

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()Dog和Cat>Animal可以让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.

Duck typing 意味着代码将简单地接受任何具有特定方法的对象.假设我们有以下代码: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天全站免登陆