基本上我想这样做:

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

我试着:

type ( obj ) == type ( string )

但这并没有起作用。

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


当前回答

使用str代替string

type ( obj ) == str

解释

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

其他回答

对于其他类型,请查看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)

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

#!/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
isinstance()

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

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

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

例子:

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

print(type(a).__name__) 

输出:“int”

print(type(b).__name__ )

输出:“东西”