基本上我想这样做:

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

我试着:

type ( obj ) == type ( string )

但这并没有起作用。

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


当前回答

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

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

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

其他回答

isinstance工作原理:

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

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

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

if obj is None: obj = MyClass()

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

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

type( x ) == type( [] )

字符串检查:

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

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

x is None

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

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

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

您可以比较类的检查级别。

#!/usr/bin/env python
#coding:utf8

class A(object):
    def t(self):
        print 'A'
    def r(self):
        print 'rA',
        self.t()

class B(A):
    def t(self):
        print 'B'

class C(A):
    def t(self):
        print 'C'

class D(B, C):
    def t(self):
        print 'D',
        super(D, self).t()

class E(C, B):
    pass

d = D()
d.t()
d.r()

e = E()
e.t()
e.r()

print isinstance(e, D) # False
print isinstance(e, E) # True
print isinstance(e, C) # True
print isinstance(e, B) # True
print isinstance(e, (A,)) # True
print e.__class__ >= A, #False
print e.__class__ <= C, #False
print e.__class__ <  E, #False
print e.__class__ <= E  #True

Type在某些类上不起作用。如果你不确定对象的类型,使用__class__方法,如下所示:

>>>obj = 'a string'
>>>obj.__class__ == str
True

也请参阅这篇文章- http://www.siafoo.net/article/56