isinstance() 和 type() 有什么区别?

使用type()与isinstance()都能判断变量的类型类型
type(a) is types.StringType 与 isinstance(a, str) 效果是一样的,那么有什么区别吗?

阅读 5.2k
1 个回答

1、isinstance()从名字上看,只能够判断实例是否为那种类型,又或者其基类类型(派生类实例中含有基类的信息)。

2、type()则明确显示出该实例的类型(相当于查看该实例的__class__属性),无论这个类由哪一个类派生而来,type所表示的都是直接生成该实例的类的类型。

#! /usr/bin/python


class Base(object):
	def __init__(self):
		pass

class A(Base):
	def __init__(self):
		pass


baseobj = Base()
a = A()

print isinstance(baseobj,Base)  #True  baseobj is an instance of Base
print isinstance(a,Base)        #True  a is an instance of Base

print type(baseobj) is Base     #True  type of baseobj is Base
print baseobj.__class__ is Base
print type(a) is Base           #False type of a is A

比较有意思的是type和object这两个对象。
看看这个你就会知道

isinstance(type,object) #True
isinstance(object,type) #True

这两个家伙互为对方的实例。你可以点击这里来了解一下。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题