如何比较Python中对象的类型?

Joa*_*nge 152 python types compare

基本上我想这样做:

obj = 'str'
type ( obj ) == string
Run Code Online (Sandbox Code Playgroud)

我试过了:

type ( obj ) == type ( string )
Run Code Online (Sandbox Code Playgroud)

它不起作用.

另外,其他类型呢?例如,我无法复制NoneType.

ant*_*ony 222

isinstance()
Run Code Online (Sandbox Code Playgroud)

在你的情况下,isinstance("this is a string", str)将返回True.

您可能还想阅读:http://www.canonical.org/~kragen/isinstance/

  • 我会说你(OP)应该*肯定*读取引用的链接,这提供了很多细节,为什么检查对象的类型通常是一个坏主意,以及你可能应该做的事情. (4认同)
  • 来自内存isinstance(obj,basestring)也会拾取unicode字符串... (3认同)
  • 你应该使用basetr,而不是str.否则你不会选择unicode.(虽然对于3.x我认为str*是*basetr) (2认同)

fen*_*aun 36

isinstance 作品:

if isinstance(obj, MyClass): do_foo(obj)
Run Code Online (Sandbox Code Playgroud)

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

编辑:对于无类型,您可以简单地执行:

if obj is None: obj = MyClass()
Run Code Online (Sandbox Code Playgroud)


S.L*_*ott 32

首先,避免所有类型比较.他们非常非常需要.有时,它们有助于检查函数中的参数类型 - 即使这种情况很少见.错误的类型数据会引发异常,这就是您所需要的全部内容.

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

type(9) is int
type(2.5) is float
type('x') is str
type(u'x') is unicode
type(2+3j) is complex
Run Code Online (Sandbox Code Playgroud)

还有一些其他案例.

isinstance( 'x', basestring )
isinstance( u'u', basestring )
isinstance( 9, int )
isinstance( 2.5, float )
isinstance( (2+3j), complex )
Run Code Online (Sandbox Code Playgroud)

没有,BTW,从不需要任何这种类型检查.None是NoneType的唯一实例.None对象是Singleton.只需检查无

variable is None
Run Code Online (Sandbox Code Playgroud)

顺便说一句,一般不要使用上述内容.使用普通异常和Python自己的自然多态.

  • 如果您正在验证来自DSL的输入,则需要所有这些,甚至是"NoneType".如果参数可以是`str`,`unicode`或`None`怎么办?`isinstance(x,(str,unicode,types.NoneType))`比检查'None`要清晰得多.如果您正在构建用于延迟计算的工具,或者如果您要启动长期或资源密集型流程,那么在某些自定义验证步骤中提前捕获"类型"错误是很有价值的.这是我曾经研究过的几乎所有科学计算项目的关键部分.在我看过的所有开发项目中,更多的需要这个而不是. (3认同)

Pao*_*ino 23

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

>>> import types
>>> x = "mystring"
>>> isinstance(x, types.StringType)
True
>>> x = 5
>>> isinstance(x, types.IntType)
True
>>> x = None
>>> isinstance(x, types.NoneType)
True
Run Code Online (Sandbox Code Playgroud)

PS Typechecking是一个坏主意.


Joh*_*uhy 14

你可以随时使用这个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)
Run Code Online (Sandbox Code Playgroud)

通常有更好的方法,特别是最近的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
Run Code Online (Sandbox Code Playgroud)

注意最后一种情况:NoneTypepython中只有一个实例,即None.你会在异常中看到很多NoneType(TypeError: 'NoneType' object is unsubscriptable- 一直发生在我身上......)但你几乎不需要在代码中引用它.

最后,正如fengshaun所指出的,在python中进行类型检查并不总是一个好主意.使用该值就好像它是您期望的类型,捕获(或允许传播)由它产生的异常更加pythonic.

  • 就其价值而言,isinstance() 是检查 Python 类型的首选方法(当您必须这样做时)。 (2认同)

tra*_*nes 11

使用isinstance(object, type)。如上所述,如果您知道正确的,则很容易使用type,例如,

isinstance('dog', str) ## gives bool True
Run Code Online (Sandbox Code Playgroud)

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

import numpy as np 
a = np.array([1,2,3]) 
isinstance(a,np.array) ## breaks
Run Code Online (Sandbox Code Playgroud)

但你可以这样做:

y = type(np.array([1]))
isinstance(a,y) ## gives bool True 
Run Code Online (Sandbox Code Playgroud)

y因此,我建议使用要检查的对象类型(例如,)实例化变量(在本例中type(np.array())),然后使用isinstance.


Jar*_*die 6

你非常接近!string是一个模块,而不是一个类型.您可能希望比较obj字符串的类型对象的类型,即str:

type(obj) == str  # this works because str is already a type
Run Code Online (Sandbox Code Playgroud)

或者:

type(obj) == type('')
Run Code Online (Sandbox Code Playgroud)

注意,在Python 2中,如果obj是unicode类型,则上述两者都不起作用.也不会isinstance().请参阅约翰对这篇文章的评论,了解如何解决这个问题......我一直试图记住它大约10分钟,但是有一个记忆块!

  • 使用带有isinstance()的basestring来获取str和unicode. (2认同)

Nei*_*eil 6

使用 str 而不是字符串

type ( obj ) == str
Run Code Online (Sandbox Code Playgroud)

解释

>>> a = "Hello"
>>> type(a)==str
True
>>> type(a)
<type 'str'>
>>>
Run Code Online (Sandbox Code Playgroud)


Ste*_*ini 5

这是因为你必须写

s="hello"
type(s) == type("")
Run Code Online (Sandbox Code Playgroud)

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

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

除了你的代码想要一个特定类型的实例这个事实之外,这个类型并没有真正告诉你多少,不管你是否可以拥有一个完全不同类型的另一个实例,因为它实现了相同的接口.

例如,假设您有此代码

def firstElement(parameter):
    return parameter[0]
Run Code Online (Sandbox Code Playgroud)

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

import types

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

这降低了这个例程的可重用性.如果传递列表,字符串或numpy.array,它将无法工作.更好的是

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

但是这样做没有意义:如果协议不满意,参数[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]
Run Code Online (Sandbox Code Playgroud)

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