有没有一种简单的方法来确定变量是列表、字典还是其他什么?
当前回答
type()是比isinstance()更好的解决方案,尤其是对于布尔值:
True和False只是python中表示1和0的关键字。因此
isinstance(True, int)
and
isinstance(False, int)
两者都返回True。两个布尔值都是整数的实例。然而,type()更聪明:
type(True) == int
返回False。
其他回答
在对象的实例上,还具有:
__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中选择)中,类和类型已经合并,这有时会导致意外的结果。主要是因为这个原因,我最喜欢的测试类型/类的方法是使用内置函数。
除了前面的答案之外,值得一提的是collections.abc的存在,它包含几个补充duck类型的抽象基类(abc)。
例如,不必显式检查某项内容是否为列表,而是:
isinstance(my_obj, list)
如果您只想查看所拥有的对象是否允许获取项目,可以使用collections.abc.Sequence:
from collections.abc import Sequence
isinstance(my_obj, Sequence)
如果您对允许获取、设置和删除项目(即可变序列)的对象非常感兴趣,那么您可以选择collections.abc.MutableSequence。
这里还定义了许多其他ABC,可以用作映射的对象的映射、Iterable、Callable等。所有这些的完整列表可以在collections.abc的文档中看到。
使用类型():
>>> a = []
>>> type(a)
<type 'list'>
>>> f = ()
>>> type(f)
<type 'tuple'>
可以使用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
value = 12
print(type(value)) # will return <class 'int'> (means integer)
或者你可以这样做
value = 12
print(type(value) == int) # will return true
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录