To get the type of an object, you can use the built-in type()
function.
(要获取对象的类型,可以使用内置的type()
函数。)
Passing an object as the only parameter will return the type object of that object: (将对象作为唯一参数传递将返回该对象的类型对象:)
>>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
True
>>> type({})
<type 'dict'>
>>> type([])
<type 'list'>
This of course also works for custom types:
(当然,这也适用于自定义类型:)
>>> class Test1 (object):
pass
>>> class Test2 (Test1):
pass
>>> a = Test1()
>>> b = Test2()
>>> type(a) is Test1
True
>>> type(b) is Test2
True
Note that type()
will only return the immediate type of the object, but won't be able to tell you about type inheritance.
(请注意, type()
将仅返回对象的直接类型,但不能告诉您类型继承。)
>>> type(b) is Test1
False
To cover that, you should use the isinstance
function.
(为此,您应该使用isinstance
函数。)
This of course also works for built-in types: (当然,这也适用于内置类型:)
>>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
True
isinstance()
is usually the preferred way to ensure the type of an object because it will also accept derived types.
(通常, isinstance()
是确保对象类型的首选方法,因为它还将接受派生类型。)
So unless you actually need the type object (for whatever reason), using isinstance()
is preferred over type()
. (因此,除非您实际上需要类型对象(无论出于何种原因),否则使用isinstance()
优先于type()
。)
The second parameter of isinstance()
also accepts a tuple of types, so it's possible to check for multiple types at once.
(isinstance()
的第二个参数也接受类型的元组,因此可以一次检查多个类型。)
isinstance
will then return true, if the object is of any of those types: (如果对象属于以下任何类型,则isinstance
将返回true:)
>>> isinstance([], (tuple, list, set))
True