在 Python 中检查类型的规范方法是什么? [英] What's the canonical way to check for type in Python?
问题描述
检查给定对象是否属于给定类型的最佳方法是什么?如何检查对象是否继承自给定类型?
假设我有一个对象 o
.如何检查它是否是 str
?
检查 o
是否是 str
的实例或 str的任何子类代码>,使用isinstance(这将是规范"方式):
if isinstance(o, str):
检查o
的类型是否正好是str
(排除子类):
如果 type(o) 是 str:
以下也有效,并且在某些情况下很有用:
if issubclass(type(o), str):
有关相关信息,请参阅 Python 库参考中的内置函数.>
再注意:在这种情况下,如果您使用的是 Python 2,您可能实际上想要使用:
if isinstance(o, basestring):
因为这也会捕获 Unicode 字符串(unicode
不是 str
的子类;str
和 unicode
都是 basestring
).请注意,basestring
在 Python 3 中不再存在,其中有 严格分离 字符串 (str
)和二进制数据(字节
).
或者,isinstance
接受一个类元组.如果 o
是任何 (str, unicode)
的任何子类的实例,这将返回 True
:
if isinstance(o, (str, unicode)):
What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?
Let's say I have an object o
. How do I check whether it's a str
?
To check if o
is an instance of str
or any subclass of str
, use isinstance (this would be the "canonical" way):
if isinstance(o, str):
To check if the type of o
is exactly str
(exclude subclasses):
if type(o) is str:
The following also works, and can be useful in some cases:
if issubclass(type(o), str):
See Built-in Functions in the Python Library Reference for relevant information.
One more note: in this case, if you're using Python 2, you may actually want to use:
if isinstance(o, basestring):
because this will also catch Unicode strings (unicode
is not a subclass of str
; both str
and unicode
are subclasses of basestring
). Note that basestring
no longer exists in Python 3, where there's a strict separation of strings (str
) and binary data (bytes
).
Alternatively, isinstance
accepts a tuple of classes. This will return True
if o
is an instance of any subclass of any of (str, unicode)
:
if isinstance(o, (str, unicode)):
这篇关于在 Python 中检查类型的规范方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!