有没有一种简单的方法来确定变量是列表、字典还是其他什么?


当前回答

使用类型()

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__我们可以读

其他回答

通常,您可以从具有类名的对象中提取字符串,

str_class = object.__class__.__name__

并将其用于比较,

if str_class == 'dict':
    # blablabla..
elif str_class == 'customclass':
    # blebleble..

使用类型()

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'>

可以使用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