Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

python - 确定对象的类型?(Determine the type of an object?)

Is there a simple way to determine if a variable is a list, dictionary, or something else?

(有没有一种简单的方法来确定变量是列表,字典还是其他?)

I am getting an object back that may be either type and I need to be able to tell the difference.

(我回来的对象可能是任何一种类型,我需要能够分辨出两者之间的区别。)

  ask by Justin Ethier translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...