python如何判断对象的类型

989次阅读
没有评论

python如何判断对象的类型

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

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
# 三个参数
>>> class X(object):
...     a = 1
...
>>> X = type('X', (object,), dict(a=1))  # 产生一个新的类型 X
>>> X
<class '__main__.X'>
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-10发表,共计522字。
新手QQ群:570568346,欢迎进群讨论 Python51学习