基本上我想这样做:

obj = 'str'
type ( obj ) == string

我试着:

type ( obj ) == type ( string )

但这并没有起作用。

还有,其他类型的呢?例如,我无法复制NoneType。


当前回答

你很接近了!字符串是模块,不是类型。你可能想比较obj的类型和字符串的类型对象,即str:

type(obj) == str  # this works because str is already a type

另外:

type(obj) == type('')

注意,在python2中,如果obj是unicode类型,那么上述两种方法都不能工作。isinstance()也不会。看看约翰对这篇文章的评论,了解如何解决这个问题……我已经试着记住它大约10分钟了,但是有一个记忆块!

其他回答

使用isinstance(object, type)。如上所述,如果你知道正确的类型,这很容易使用,例如,

isinstance('dog', str) ## gives bool True

但对于更深奥的对象,这可能很难使用。 例如:

import numpy as np 
a = np.array([1,2,3]) 
isinstance(a,np.array) ## breaks

但你可以用这个技巧:

y = type(np.array([1]))
isinstance(a,y) ## gives bool True 

所以我建议用你想检查的对象类型(例如,type(np.array())实例化一个变量(在本例中是y),然后使用isinstance。

isinstance工作原理:

if isinstance(obj, MyClass): do_foo(obj)

但是,请记住:如果它看起来像鸭子,如果它听起来像鸭子,它就是鸭子。

编辑:对于None类型,你可以简单地做:

if obj is None: obj = MyClass()

使用str代替string

type ( obj ) == str

解释

>>> a = "Hello"
>>> type(a)==str
True
>>> type(a)
<type 'str'>
>>>
isinstance()

在你的例子中,isinstance("this is a string", str)将返回True。

你可能还想读这个:http://www.canonical.org/~kragen/isinstance/

你很接近了!字符串是模块,不是类型。你可能想比较obj的类型和字符串的类型对象,即str:

type(obj) == str  # this works because str is already a type

另外:

type(obj) == type('')

注意,在python2中,如果obj是unicode类型,那么上述两种方法都不能工作。isinstance()也不会。看看约翰对这篇文章的评论,了解如何解决这个问题……我已经试着记住它大约10分钟了,但是有一个记忆块!