问题:如何在Python中比较对象的类型?

基本上我想这样做:

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

我试过了:

type ( obj ) == type ( string )

而且没有用

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

Basically I want to do this:

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

I tried:

type ( obj ) == type ( string )

and it didn’t work.

Also, what about the other types? For example, I couldn’t replicate NoneType.


回答 0

isinstance()

就您而言,isinstance("this is a string", str)将返回True

您可能还需要阅读以下内容:http : //www.canonical.org/~kragen/isinstance/

isinstance()

In your case, isinstance("this is a string", str) will return True.

You may also want to read this: http://www.canonical.org/~kragen/isinstance/


回答 1

isinstance 作品:

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

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

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

if obj is None: obj = MyClass()

isinstance works:

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

but, keep in mind: if it looks like a duck, and if it sounds like a duck, it is a duck.

EDIT: For the None type, you can simply do:

if obj is None: obj = MyClass()

回答 2

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

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

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是NoneType的唯一实例。None对象是一个Singleton。只需检查无

variable is None

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

First, avoid all type comparisons. They’re very, very rarely necessary. Sometimes, they help to check parameter types in a function — even that’s rare. Wrong type data will raise an exception, and that’s all you’ll ever need.

All of the basic conversion functions will map as equal to the type function.

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

There are a few other cases.

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

None, BTW, never needs any of this kind of type checking. None is the only instance of NoneType. The None object is a Singleton. Just check for None

variable is None

BTW, do not use the above in general. Use ordinary exceptions and Python’s own natural polymorphism.


回答 3

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

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

PS类型检查不是一个好主意。

For other types, check out the types module:

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

P.S. Typechecking is a bad idea.


回答 4

您总是可以使用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

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

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

You can always use the type(x) == type(y) trick, where y is something with known type.

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

Often there are better ways of doing that, particularly with any recent python. But if you only want to remember one thing, you can remember that.

In this case, the better ways would be:

# 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

Note the last case: there is only one instance of NoneType in python, and that is None. You’ll see NoneType a lot in exceptions (TypeError: 'NoneType' object is unsubscriptable — happens to me all the time..) but you’ll hardly ever need to refer to it in code.

Finally, as fengshaun points out, type checking in python is not always a good idea. It’s more pythonic to just use the value as though it is the type you expect, and catch (or allow to propagate) exceptions that result from it.


回答 5

你很亲密!string是模块,而不是类型。您可能要比较obj字符串的type对象和type对象的类型,即str

type(obj) == str  # this works because str is already a type

或者:

type(obj) == type('')

请注意,在Python 2中,如果obj是unicode类型,则以上两种都不起作用。也不会isinstance()。有关此问题的解决方法,请参见John对这篇文章的评论。我一直在想起它大约10分钟,但是有一个内存块!

You’re very close! string is a module, not a type. You probably want to compare the type of obj against the type object for strings, namely str:

type(obj) == str  # this works because str is already a type

Alternatively:

type(obj) == type('')

Note, in Python 2, if obj is a unicode type, then neither of the above will work. Nor will isinstance(). See John’s comments to this post for how to get around this… I’ve been trying to remember it for about 10 minutes now, but was having a memory block!


回答 6

因为你必须写

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]

但是这样做没有任何意义:如果无论如何都不满足协议,则parameter [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()调用之前引发异常。如果不进行接口检查,则将删除该文件,然后引发异常。

It is because you have to write

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

type accepts an instance and returns its type. In this case you have to compare two instances’ types.

If you need to do preemptive checking, it is better if you check for a supported interface than the type.

The type does not really tell you much, apart of the fact that your code want an instance of a specific type, regardless of the fact that you could have another instance of a completely different type which would be perfectly fine because it implements the same interface.

For example, suppose you have this code

def firstElement(parameter):
    return parameter[0]

Now, suppose you say: I want this code to accept only a tuple.

import types

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

This is reducing the reusability of this routine. It won’t work if you pass a list, or a string, or a numpy.array. Something better would be

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

but there’s no point in doing it: parameter[0] will raise an exception if the protocol is not satisfied anyway… this of course unless you want to prevent side effects or having to recover from calls that you could invoke before failing. (Stupid) example, just to make the point:

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

in this case, your code will raise an exception before running the system() call. Without interface checks, you would have removed the file, and then raised the exception.


回答 7

使用str代替字符串

type ( obj ) == str

说明

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

Use str instead of string

type ( obj ) == str

Explanation

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

回答 8

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

例如,如果我要检查的东西是一个数组:

type( x ) == type( [] )

字符串检查:

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

如果要检查无,请使用

x is None

I use type(x) == type(y)

For instance, if I want to check something is an array:

type( x ) == type( [] )

string check:

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

If you want to check against None, use is

x is None

回答 9

我认为这应该做到

if isinstance(obj, str)

i think this should do it

if isinstance(obj, str)

回答 10

类型不适用于某些类。如果不确定对象的类型,请使用__class__方法,如下所示:

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

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

Type doesn’t work on certain classes. If you’re not sure of the object’s type use the __class__ method, as so:

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

Also see this article – http://www.siafoo.net/article/56


回答 11

要获取类型,请使用__class__成员,如下所示unknown_thing.__class__

在这里说鸭嘴式是没有用的,因为它不能回答一个完美的问题。在我的应用程序代码中,我永远不需要知道某种事物的类型,但是有一种学习对象类型的方法仍然很有用。有时我需要获得实际的类来验证单元测试。因为所有可能的对象都具有相同的API,但只有一个是正确的,因此鸭子类型会妨碍您的输入。另外,有时我正在维护其他人的代码,而且我不知道我传递了什么样的对象。这是诸如Python之类的动态类型语言的最大问题。版本1非常易于开发。第2版​​让您不知所措,尤其是如果您没有编写第1版时。因此,有时候,当我使用未编写的函数时,我需要知道参数的类型,

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

To get the type, use the __class__ member, as in 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.

That’s where the __class__ parameter comes in handy. That (as far as I can tell) is the best way (maybe the only way) to get an object’s type.


回答 12

使用isinstance(object, type)。如上所述,如果您知道正确的方法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 

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

Use isinstance(object, type). As above this is easy to use if you know the correct type, e.g.,

isinstance('dog', str) ## gives bool True

But for more esoteric objects, this can be difficult to use. For example:

import numpy as np 
a = np.array([1,2,3]) 
isinstance(a,np.array) ## breaks

but you can do this trick:

y = type(np.array([1]))
isinstance(a,y) ## gives bool True 

So I recommend instantiating a variable (y in this case) with a type of the object you want to check (e.g., type(np.array())), then using isinstance.


回答 13

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

#!/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

You can compare classes for check level.

#!/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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。