确定对象的类型?

新手上路,请多包涵

有没有一种简单的方法来确定变量是列表、字典还是其他东西?

原文由 Justin Ethier 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 642
2 个回答

有两个内置函数可以帮助您识别对象的类型。如果您需要对象的确切类型,您可以使用 type()isinstance()检查 对象的类型。通常,你想使用 isinstance() 因为它非常健壮并且还支持类型继承。


要获取对象的实际类型,请使用内置的 type() 函数。将对象作为唯一参数传递将返回该对象的类型对象:

 >>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
True

这当然也适用于自定义类型:

 >>> class Test1 (object):
        pass
>>> class Test2 (Test1):
        pass
>>> a = Test1()
>>> b = Test2()
>>> type(a) is Test1
True
>>> type(b) is Test2
True

请注意, type() 只会返回对象的直接类型,但无法告诉您有关类型继承的信息。

 >>> type(b) is Test1
False

为了解决这个问题,您应该使用 isinstance 函数。这当然也适用于内置类型:

 >>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
True

isinstance() 通常是确保对象类型的首选方式,因为它也接受派生类型。因此,除非您确实需要类型对象(无论出于何种原因),否则使用 isinstance() 优于 type()

isinstance() 的第二个参数也接受类型元组,因此可以一次检查多种类型。 isinstance 如果对象属于以下任何类型,则返回 true:

 >>> isinstance([], (tuple, list, set))
True

原文由 poke 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 type()

 >>> a = []
>>> type(a)
<type 'list'>
>>> f = ()
>>> type(f)
<type 'tuple'>

原文由 brettkelly 发布,翻译遵循 CC BY-SA 4.0 许可协议

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