基本上我想这样做:

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

我试着:

type ( obj ) == type ( string )

但这并没有起作用。

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


当前回答

使用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()

对于其他类型,请查看types模块:

>>> import types
>>> x = "mystring"
>>> isinstance(x, types.StringType)
True
>>> x = 5
>>> isinstance(x, types.IntType)
True
>>> x = None
>>> isinstance(x, types.NoneType)
True

注:类型检查是个坏主意。

我想这个就可以了

if isinstance(obj, str)

因为type返回一个对象,所以可以使用object.name访问对象的名称

例子:

years = 5
user = {'name':'Smith', 'age':20}

print(type(a).__name__) 

输出:“int”

print(type(b).__name__ )

输出:“东西”

我用type(x) == type(y)

例如,如果我想检查一个数组:

type( x ) == type( [] )

字符串检查:

type( x ) == type( '' ) or type( x ) == type( u'' )

如果您想检查None,请使用is

x is None