基本上我想这样做:

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

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

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


我想这个就可以了

if isinstance(obj, 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

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


isinstance工作原理:

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

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

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

if obj is None: obj = MyClass()

您总是可以使用type(x) == type(y)技巧,其中y是具有已知类型的东西。

# check if x is a regular string
type(x) == type('')
# check if x is an integer
type(x) == type(1)
# check if x is a NoneType
type(x) == type(None)

通常有更好的方法来做到这一点,特别是对于任何最新的python。但如果你只想记住一件事,你可以记住它。

在这种情况下,更好的方法是:

# check if x is a regular string
type(x) == str
# check if x is either a regular string or a unicode string
type(x) in [str, unicode]
# alternatively:
isinstance(x, basestring)
# check if x is an integer
type(x) == int
# check if x is a NoneType
x is None

注意最后一种情况:在python中只有一个NoneType实例,那就是None。你会在异常中看到很多NoneType (TypeError: 'NoneType'对象是不可下标的-发生在我身上..),但你几乎不需要在代码中引用它。

最后,正如fengshaun所指出的,python中的类型检查并不总是一个好主意。更python化的做法是只使用值,就好像它是您所期望的类型一样,并捕获(或允许传播)由此产生的异常。


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

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

type( x ) == type( [] )

字符串检查:

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

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

x is None

首先,避免所有类型比较。它们很少是必要的。有时,它们有助于检查函数中的参数类型——即使这种情况也很少见。错误类型的数据将引发异常,而这正是您所需要的。

所有基本转换函数都将映射为类型函数。

type(9) is int
type(2.5) is float
type('x') is str
type(u'x') is unicode
type(2+3j) is complex

还有其他一些情况。

isinstance( 'x', basestring )
isinstance( u'u', basestring )
isinstance( 9, int )
isinstance( 2.5, float )
isinstance( (2+3j), complex )

顺便说一句,None从来不需要任何这种类型的检查。None是唯一的实例。None对象是一个单例对象。只检查None

variable is None

顺便说一下,一般情况下不要使用上述方法。使用普通异常和Python本身的自然多态。


因为你必须写作

s="hello"
type(s) == type("")

Type接受实例并返回其类型。在这种情况下,您必须比较两个实例的类型。

如果需要执行抢占式检查,最好检查受支持的接口,而不是类型。

除了你的代码需要一个特定类型的实例之外,类型并没有真正告诉你什么,不管你可以有另一个完全不同类型的实例,这是完全没问题的,因为它实现了相同的接口。

例如,假设您有以下代码

def firstElement(parameter):
    return parameter[0]

现在,假设您说:我希望这段代码只接受一个元组。

import types

def firstElement(parameter):
    if type(parameter) != types.TupleType:
         raise TypeError("function accepts only a tuple")
    return parameter[0]

这降低了这个例程的可重用性。如果你传递一个列表,或者字符串,或者numpy。array,它就不起作用。更好的做法是

def firstElement(parameter):
    if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
        raise TypeError("interface violation")
    return parameter[0]

但是这样做没有任何意义:如果协议不满足,参数[0]将引发异常……当然,除非您想防止副作用,或者必须从失败前可能调用的调用中恢复。(愚蠢的)例子,只是为了说明这一点:

def firstElement(parameter):
    if not (hasattr(parameter, "__getitem__") and callable(getattr(parameter,"__getitem__"))):
        raise TypeError("interface violation")
    os.system("rm file")
    return parameter[0]

在这种情况下,您的代码将在运行system()调用之前引发异常。如果没有接口检查,您将删除该文件,然后引发异常。


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

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

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


要获取类型,使用__class__成员,如unknown_thing.__class__

Talk of duck-typing is useless here because it doesn't answer a perfectly good question. In my application code I never need to know the type of something, but it's still useful to have a way to learn an object's type. Sometimes I need to get the actual class to validate a unit test. Duck typing gets in the way there because all possible objects have the same API, but only one is correct. Also, sometimes I'm maintaining somebody else's code, and I have no idea what kind of object I've been passed. This is my biggest problem with dynamically typed languages like Python. Version 1 is very easy and quick to develop. Version 2 is a pain in the buns, especially if you didn't write version 1. So sometimes, when I'm working with a function I didn't write, I need to know the type of a parameter, just so I know what methods I can call on it.

这就是__class__参数派上用场的地方。这(据我所知)是获取对象类型的最佳方法(可能是唯一的方法)。


使用str代替string

type ( obj ) == str

解释

>>> a = "Hello"
>>> type(a)==str
True
>>> type(a)
<type '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(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。


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

例子:

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

print(type(a).__name__) 

输出:“int”

print(type(b).__name__ )

输出:“东西”