基本上我想这样做:
obj = 'str'
type ( obj ) == string
我试过:
type ( obj ) == type ( string )
它没有用。
另外,其他类型呢?例如,我无法复制NoneType
.
isinstance()
在您的情况下,isinstance("this is a string", str)
将返回True
.
您可能还想阅读以下内容:http: //www.canonical.org/~kragen/isinstance/
isinstance
作品:
if isinstance(obj, MyClass): do_foo(obj)
但是,请记住:如果它看起来像一只鸭子,如果它听起来像一只鸭子,那么它就是一只鸭子。
编辑:对于 None 类型,您可以简单地执行以下操作:
if obj is None: obj = MyClass()
首先,避免所有类型比较。它们非常非常少需要。有时,它们有助于检查函数中的参数类型——即使这种情况很少见。错误的类型数据会引发异常,这就是您所需要的。
所有基本转换函数都将映射为等于类型函数。
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 对象是一个单例。只需检查无
variable is None
顺便说一句,一般不要使用上述内容。使用普通异常和 Python 自身的自然多态性。
对于其他类型,请查看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 类型检查是个坏主意。
你总是可以使用这个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。
你很亲近!string
是一个模块,而不是一个类型。您可能希望将 的类型obj
与字符串的类型对象进行比较,即str
:
type(obj) == str # this works because str is already a type
或者:
type(obj) == type('')
请注意,在 Python 2 中,如果obj
是 unicode 类型,则以上都不起作用。也不会isinstance()
。请参阅约翰对这篇文章的评论,了解如何解决这个问题......我已经尝试记住它大约 10 分钟了,但是有一个记忆块!
使用 str 而不是字符串
type ( obj ) == str
解释
>>> a = "Hello"
>>> type(a)==str
True
>>> type(a)
<type 'str'>
>>>
使用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
.
这是因为你必须写
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(x) == type(y)
例如,如果我想检查一个数组:
type( x ) == type( [] )
字符串检查:
type( x ) == type( '' ) or type( x ) == type( u'' )
如果你想检查 None,使用 is
x is None
我认为这应该这样做
if isinstance(obj, str)
类型不适用于某些类。如果您不确定对象的类型,请使用该__class__
方法,如下所示:
>>>obj = 'a string'
>>>obj.__class__ == str
True
另见这篇文章 - http://www.siafoo.net/article/56
要获取类型,请使用__class__
成员,如unknown_thing.__class__
在这里谈论鸭式打字是没有用的,因为它不能回答一个非常好的问题。在我的应用程序代码中,我从不需要知道某物的类型,但是有一种方法来学习对象的类型仍然很有用。有时我需要获取实际的类来验证单元测试。因为所有可能的对象都有相同的 API,但只有一个是正确的。另外,有时我在维护别人的代码,我不知道我传递了什么样的对象。这是我对 Python 等动态类型语言的最大问题。第 1 版开发起来非常简单快捷。版本 2 是个麻烦事,尤其是如果您没有编写版本 1。所以有时,当我使用我没有编写的函数时,我需要知道参数的类型,
这就是__class__
参数派上用场的地方。那(据我所知)是获取对象类型的最佳方法(也许是唯一方法)。
您可以比较检查级别的类。
#!/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