当前位置: 首页 > 图灵资讯 > 行业资讯> python如何判断对象的类型

python如何判断对象的类型

来源:图灵python
时间: 2025-01-08 14:44:02

type() 函数如果你只有第一个参数则返回对象的类型,三个参数返回新的类型对象。与之类似的是isinstance()函数,但二者有一定的区别。

(推荐教程:Python入门教程)

isinstance() 与 type() 区别:

type() 不会认为子类是一种父类类型,不考虑继承关系。

isinstance() 会认为子类是一种父类类型,考虑继承关系。

如果要判断两个类型是否相同推荐使用 isinstance()。

语法:

type(object)
type(name,bases,dict)

代码实现:

#一个参数实例
>>>type(1)
<type'int'>
>>>type('phpcn')
<type'str'>
>>>type([2])
<type'list'>
>>>type({0:'zero'})
<type'dict'>
>>>x=1
>>>type(x)==int#判断类型是否相等True
#三个参数
>>>classX(object):
...a=1
...
>>>X=type('X',(object,),dict(a=1))#产生一个新的类型X
>>>X
<class'__main__.X'>