多态性在Python中如何工作? [英] How does polymorphism work in Python?

查看:73
本文介绍了多态性在Python中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,如果有任何原因,他来自Java背景.

I'm new to Python... and coming from a mostly Java background, if that accounts for anything.

我正在尝试了解Python中的多态性.也许问题在于我期望将我已经知道的概念投影到Python中.但我整理了以下测试代码:

I'm trying to understand polymorphism in Python. Maybe the problem is that I'm expecting the concepts I already know to project into Python. But I put together the following test code:

class animal(object):
    "empty animal class"

class dog(animal):
    "empty dog class"

myDog = dog()
print myDog.__class__ is animal
print myDog.__class__ is dog

从我惯用的多态性(例如Java的instanceof),我希望这两个语句都能显示为真,因为狗是动物也是是一只狗但是我的输出是:

From the polymorphism I'm used to (e.g. java's instanceof), I would expect both of these statements to print true, as an instance of dog is an animal and also is a dog. But my output is:

False
True

我想念什么?

推荐答案

Python中的is运算符检查两个参数是否引用内存中的同一对象;它不像C#中的is运算符.

The is operator in Python checks that the two arguments refer to the same object in memory; it is not like the is operator in C#.

从文档中:

运算符是否在测试对象标识:并且仅当x和y是同一对象时,x y才为true. x不是y会产生反真值.

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.

在这种情况下,您要查找的是 isinstance .

What you're looking for in this case is isinstance.

如果object参数是classinfo参数或其(直接或间接)子类的实例,则返回true.

Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof.

>>> class animal(object): pass

>>> class dog(animal): pass

>>> myDog = dog()
>>> isinstance(myDog, dog)
True
>>> isinstance(myDog, animal)
True

但是,惯用的Python指示您(几乎)从不进行类型检查,而是依靠 duck-输入以获取多态行为.使用isinstance理解继承是没有问题的,但是通常应该在生产"代码中避免使用它.

However, idiomatic Python dictates that you (almost) never do type-checking, but instead rely on duck-typing for polymorphic behavior. There's nothing wrong with using isinstance to understand inheritance, but it should generally be avoided in "production" code.

这篇关于多态性在Python中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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