有没有一种简单的方法来确定变量是列表、字典还是其他什么?
当前回答
可以使用type()或isinstance()。
>>> type([]) is list
True
请注意,通过在当前作用域中分配同名变量,可以删除列表或任何其他类型。
>>> the_d = {}
>>> t = lambda x: "aight" if type(x) is dict else "NOPE"
>>> t(the_d) 'aight'
>>> dict = "dude."
>>> t(the_d) 'NOPE'
上面我们看到dict被重新分配给一个字符串,因此测试:
type({}) is dict
…失败。
要解决此问题并更谨慎地使用type():
>>> import __builtin__
>>> the_d = {}
>>> type({}) is dict
True
>>> dict =""
>>> type({}) is dict
False
>>> type({}) is __builtin__.dict
True
其他回答
有两个内置函数可以帮助您识别对象的类型。如果需要对象的确切类型,可以使用type(),并使用isinstance()检查对象的类型。通常,您希望在大多数情况下使用isinstance(),因为它非常健壮,也支持类型继承。
要获取对象的实际类型,可以使用内置的type()函数。将对象作为唯一参数传递将返回该对象的类型对象:
>>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
True
这当然也适用于自定义类型:
>>> class Test1 (object):
pass
>>> class Test2 (Test1):
pass
>>> a = Test1()
>>> b = Test2()
>>> type(a) is Test1
True
>>> type(b) is Test2
True
请注意,type()只返回对象的直接类型,但不能告诉您类型继承。
>>> type(b) is Test1
False
为此,您应该使用isinstance函数。这当然也适用于内置类型:
>>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
True
isinstance()通常是确保对象类型的首选方法,因为它也接受派生类型。因此,除非您实际需要类型对象(无论出于什么原因),否则使用isinstance()比使用type()更可取。
isinstance()的第二个参数也接受一个类型元组,因此可以同时检查多个类型。如果对象属于以下任何类型,isinstance将返回true:
>>> isinstance([], (tuple, list, set))
True
在对象的实例上,还具有:
__class__
属性下面是一个来自Python3.3控制台的示例
>>> str = "str"
>>> str.__class__
<class 'str'>
>>> i = 2
>>> i.__class__
<class 'int'>
>>> class Test():
... pass
...
>>> a = Test()
>>> a.__class__
<class '__main__.Test'>
请注意,在python3.x和NewStyle类(可从Python2.6中选择)中,类和类型已经合并,这有时会导致意外的结果。主要是因为这个原因,我最喜欢的测试类型/类的方法是使用内置函数。
虽然这些问题很古老,但我在自己找到正确的方法时偶然发现了这一点,我认为它仍然需要澄清,至少对于Python2.x是如此(没有检查Python3,但由于这个问题出现在此类版本中的经典类中,这可能无关紧要)。
在这里,我试图回答标题的问题:如何确定任意对象的类型?其他关于使用或不使用isinstance的建议在许多评论和回答中都很好,但我并没有解决这些问题。
type()方法的主要问题是它不能在旧样式实例中正常工作:
class One:
pass
class Two:
pass
o = One()
t = Two()
o_type = type(o)
t_type = type(t)
print "Are o and t instances of the same class?", o_type is t_type
执行此代码段将产生:
Are o and t instances of the same class? True
我认为,这并不是大多数人所期望的。
__class__方法最接近正确性,但在一个关键的情况下,它不起作用:当传入的对象是旧式类(不是实例!)时,因为这些对象缺少这种属性。
这是我能想到的以一致方式满足此类合法问题的最小代码片段:
#!/usr/bin/env python
from types import ClassType
#we adopt the null object pattern in the (unlikely) case
#that __class__ is None for some strange reason
_NO_CLASS=object()
def get_object_type(obj):
obj_type = getattr(obj, "__class__", _NO_CLASS)
if obj_type is not _NO_CLASS:
return obj_type
# AFAIK the only situation where this happens is an old-style class
obj_type = type(obj)
if obj_type is not ClassType:
raise ValueError("Could not determine object '{}' type.".format(obj_type))
return obj_type
value = 12
print(type(value)) # will return <class 'int'> (means integer)
或者你可以这样做
value = 12
print(type(value) == int) # will return true
使用类型()
x='hello this is a string'
print(type(x))
输出
<class 'str'>
要仅提取str,请使用
x='this is a string'
print(type(x).__name__)#you can use__name__to find class
输出
str
如果使用类型(变量)__name__我们可以读
推荐文章
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- 存在类型是什么?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试
- 插入一行到熊猫数据框架
- 要列出Pandas DataFrame列
- 如何连接列在Postgres选择?
- 在Django模型中存储电话号码的最佳方法是什么?
- 从导入的模块中模拟函数
- 在内存的哪里我的变量存储在C?