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

发布于 2024-07-16 01:21:51 字数 218 浏览 5 评论 0原文

基本上我想这样做:

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

只怪假的太真实 2024-07-23 01:21:51
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/

浪荡不羁 2024-07-23 01:21:51

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

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

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 对象是一个单例对象。 只需检查 None

variable is None

BTW,一般不要使用上述内容。 使用普通异常和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.

尬尬 2024-07-23 01:21:51

isinstance 有效:

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

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

编辑:对于 None 类型,您可以简单地执行以下操作:

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()
心清如水 2024-07-23 01:21:51

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

>>> 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.

天荒地未老 2024-07-23 01:21:51

您始终可以使用 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' object is unsubscriptable - 一直发生在我身上..),但您几乎不需要在代码中引用它。

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

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.

小忆控 2024-07-23 01:21:51

使用 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

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.

千笙结 2024-07-23 01:21:51

你非常接近! string 是一个模块,而不是类型。 您可能想要将 obj 的类型与字符串对象的类型(即 str)进行比较:

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

或者:

type(obj) == type('')

注意,在 Python 2 中,如果 obj是 unicode 类型,那么以上都不起作用。 isinstance() 也不会。 请参阅约翰对这篇文章的评论,了解如何解决这个问题...我已经尝试记住它大约 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!

罗罗贝儿 2024-07-23 01:21:51

使用 str 代替 string

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'>
>>>
陌伤浅笑 2024-07-23 01:21:51

这是因为你必须编写

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() 调用之前引发异常。 如果没有接口检查,您将删除该文件,然后引发异常。

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.

咆哮 2024-07-23 01:21:51

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

例如,如果我想检查某个东西是否为数组:

type( x ) == type( [] )

string check:

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

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

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
她说她爱他 2024-07-23 01:21:51

我认为这应该可以

if isinstance(obj, str)

i think this should do it

if isinstance(obj, str)
凶凌 2024-07-23 01:21:51

要获取类型,请使用 __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.

送君千里 2024-07-23 01:21:51

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

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

另请参阅这篇文章
Python 中的类型检查 - Siafoo

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
Type Checking in Python - Siafoo

岛歌少女 2024-07-23 01:21:51

您可以比较班级以检查级别。

#!/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
离不开的别离 2024-07-23 01:21:51

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

示例:

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

print(type(a).__name__) 

output: 'int'

print(type(b).__name__ )

output: '听写'

Because type returns an object, you can access de the name of the object using object.name

Example:

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

print(type(a).__name__) 

output: 'int'

print(type(b).__name__ )

output: 'dict'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文