问题描述
我是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#.
从文档中:
在这种情况下,您要查找的是 isinstance
.
What you're looking for in this case is isinstance
.
>>> 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中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!