多态性在Python中是如何工作的?

2024-06-16 13:54:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不熟悉。。。如果这能说明什么的话,它主要来自Java背景。

我试图理解Python中的多态性。也许问题是我希望我已经知道的概念能够投射到Python中。但我整理了以下测试代码:

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的{})来看,我希望这两个语句都能打印为true,因为dog的一个实例是一个动物,而且也是一个狗。但我的产出是:

False
True

我错过了什么?


Tags: 概念objectisjava整理classempty背景
3条回答

菲莫和马克已经回答了你的问题。但这也是Python中多态性的一个例子,但它不像基于继承的例子那么明显。

class wolf(object): 
    def bark(self):
        print "hooooowll"

class dog(object): 
    def bark(self):
        print "woof"


def barkforme(dogtype):
    dogtype.bark()


my_dog = dog()
my_wolf = wolf()
barkforme(my_dog)
barkforme(my_wolf)

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

From the docs

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.

在这种情况下,您需要的是^{}

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-typing进行多态行为。使用isinstance来理解继承并没有什么错,但是通常应该在“生产”代码中避免它。

尝试isinstance(myDog, dog)resp。isinstance(myDog, animal)

相关问题 更多 >