本文引用非常靠谱的一篇回答:
https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance
isinstance 满足继承的和基类是一样类型的。
下面是为什么isinstance比type更好的原因:
class Vehicle:
pass
class Truck(Vehicle):
pass
这个例子中 truck对象是一个Vehicle, 但你会得到如下:
isinstance(Vehicle(), Vehicle) # returns True
type(Vehicle()) == Vehicle # returns True
isinstance(Truck(), Vehicle) # returns True
type(Truck()) == Vehicle # returns False, and this probably won't be what you want.
上面的结果type(Truck()) == Vehicle为false, 经过输出:
\>>>print(Truck())
<__main__.Truck object at 0x00000000060A
网友评论