有没有一种简单的方法来确定变量是列表、字典还是其他什么?
当前回答
确定Python对象的类型
使用类型确定对象的类型
>>> obj = object()
>>> type(obj)
<class 'object'>
虽然它有效,但避免使用__class__之类的双下划线属性-它们在语义上不是公共的,虽然在这种情况下可能不是,但内置函数通常具有更好的行为。
>>> obj.__class__ # avoid this!
<class 'object'>
类型检查
有没有一种简单的方法来确定变量是列表、字典还是其他什么?我得到了一个可能是这两种类型的对象,我需要能够分辨出其中的区别。
好吧,这是另一个问题,不要使用类型-用法:
def foo(obj):
"""given a string with items separated by spaces,
or a list or tuple,
do something sensible
"""
if isinstance(obj, str):
obj = str.split()
return _foo_handles_only_lists_or_tuples(obj)
这涵盖了这样一种情况,即您的用户可能正在通过子类化str来做一些聪明或明智的事情-根据Liskov Substitution的原理,您希望能够在不破坏代码的情况下使用子类实例-而isinstance支持这一点。
使用摘要
更好的是,您可以从集合或数字中查找特定的抽象基类:
from collections import Iterable
from numbers import Number
def bar(obj):
"""does something sensible with an iterable of numbers,
or just one number
"""
if isinstance(obj, Number): # make it a 1-tuple
obj = (obj,)
if not isinstance(obj, Iterable):
raise TypeError('obj must be either a number or iterable of numbers')
return _bar_sensible_with_iterable(obj)
或只是不显式键入检查
或者,也许最棒的是,使用duck类型,不要显式地检查代码类型。Duck类型支持Liskov替换,更优雅,更少冗长。
def baz(obj):
"""given an obj, a dict (or anything with an .items method)
do something sensible with each key-value pair
"""
for key, value in obj.items():
_baz_something_sensible(key, value)
结论
使用类型实际获取实例的类。使用isinstance显式检查实际的子类或注册的抽象。只要在有意义的地方避免类型检查。
其他回答
确定Python对象的类型
使用类型确定对象的类型
>>> obj = object()
>>> type(obj)
<class 'object'>
虽然它有效,但避免使用__class__之类的双下划线属性-它们在语义上不是公共的,虽然在这种情况下可能不是,但内置函数通常具有更好的行为。
>>> obj.__class__ # avoid this!
<class 'object'>
类型检查
有没有一种简单的方法来确定变量是列表、字典还是其他什么?我得到了一个可能是这两种类型的对象,我需要能够分辨出其中的区别。
好吧,这是另一个问题,不要使用类型-用法:
def foo(obj):
"""given a string with items separated by spaces,
or a list or tuple,
do something sensible
"""
if isinstance(obj, str):
obj = str.split()
return _foo_handles_only_lists_or_tuples(obj)
这涵盖了这样一种情况,即您的用户可能正在通过子类化str来做一些聪明或明智的事情-根据Liskov Substitution的原理,您希望能够在不破坏代码的情况下使用子类实例-而isinstance支持这一点。
使用摘要
更好的是,您可以从集合或数字中查找特定的抽象基类:
from collections import Iterable
from numbers import Number
def bar(obj):
"""does something sensible with an iterable of numbers,
or just one number
"""
if isinstance(obj, Number): # make it a 1-tuple
obj = (obj,)
if not isinstance(obj, Iterable):
raise TypeError('obj must be either a number or iterable of numbers')
return _bar_sensible_with_iterable(obj)
或只是不显式键入检查
或者,也许最棒的是,使用duck类型,不要显式地检查代码类型。Duck类型支持Liskov替换,更优雅,更少冗长。
def baz(obj):
"""given an obj, a dict (or anything with an .items method)
do something sensible with each key-value pair
"""
for key, value in obj.items():
_baz_something_sensible(key, value)
结论
使用类型实际获取实例的类。使用isinstance显式检查实际的子类或注册的抽象。只要在有意义的地方避免类型检查。
除了前面的答案之外,值得一提的是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的文档中看到。
有两个内置函数可以帮助您识别对象的类型。如果需要对象的确切类型,可以使用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
使用类型()
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__我们可以读
使用类型():
>>> a = []
>>> type(a)
<type 'list'>
>>> f = ()
>>> type(f)
<type 'tuple'>
推荐文章
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?
- 在Python中,冒号等于(:=)是什么意思?
- Python "SyntaxError:文件中的非ascii字符'\xe2' "
- 如何从psycopg2游标获得列名列表?
- Python中dict对象的联合
- 如何有效地比较两个无序列表(不是集合)?