基本上我想这样做:
obj = 'str'
type ( obj ) == string
我试着:
type ( obj ) == type ( string )
但这并没有起作用。
还有,其他类型的呢?例如,我无法复制NoneType。
基本上我想这样做:
obj = 'str'
type ( obj ) == string
我试着:
type ( obj ) == type ( string )
但这并没有起作用。
还有,其他类型的呢?例如,我无法复制NoneType。
当前回答
使用str代替string
type ( obj ) == str
解释
>>> a = "Hello"
>>> type(a)==str
True
>>> type(a)
<type '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(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。
您可以比较类的检查级别。
#!/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
要获取类型,使用__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__参数派上用场的地方。这(据我所知)是获取对象类型的最佳方法(可能是唯一的方法)。
我想这个就可以了
if isinstance(obj, str)