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
375 views
in Technique[技术] by (71.8m points)

python - 在Python中检查类型的规范方法是什么?(What's the canonical way to check for type in Python?)

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 .

(假设我有一个对象o 。)

How do I check whether it's a str ?

(如何检查是否为str ?)

  ask by Herge translate from so

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

1 Reply

0 votes
by (71.8m points)

To check if o is an instance of str or any subclass of str , use isinstance (this would be the "canonical" way):

(要检查是否o是的实例str或的任何子类str ,使用isinstance (这将是“规范”的方式):)

if isinstance(o, str):

To check if the type of o is exactly str (exclude subclasses):

(要检查o的类型是否完全是str (不包括子类):)

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.

(有关相关信息,请参见Python库参考中的内置函数 。)

One more note: in this case, if you're using python 2, you may actually want to use:

(还有一点需要注意:在这种情况下,如果您使用的是python 2,则实际上可能要使用:)

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 ).

(因为这也会捕获Unicode字符串( unicode不是str的子类; strunicode都是basestring子类)。)

Note that basestring no longer exists in python 3, where there's a strict separation of strings ( str ) and binary data ( bytes ).

(请注意,在python 3中不再存在basestring ,在Python 3中,字符串( str )和二进制数据( bytes严格分开 。)

Alternatively, isinstance accepts a tuple of classes.

(另外, isinstance接受一个类的元组。)

This will return True if x is an instance of any subclass of any of (str, unicode):

(如果x是(str,unicode)的任何子类的实例,则将返回True:)

if isinstance(o, (str, unicode)):

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

...