python - isinstance() 和 type() 有什么区别?
PHPz
PHPz 2017-04-17 11:08:36
[Python讨论组]

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

PHPz
PHPz

学习是最好的投资!

全部回复(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

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号