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


当前回答

在对象的实例上,还具有:

__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中选择)中,类和类型已经合并,这有时会导致意外的结果。主要是因为这个原因,我最喜欢的测试类型/类的方法是使用内置函数。

其他回答

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

str_class = object.__class__.__name__

并将其用于比较,

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

在对象的实例上,还具有:

__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中选择)中,类和类型已经合并,这有时会导致意外的结果。主要是因为这个原因,我最喜欢的测试类型/类的方法是使用内置函数。

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

在许多实际情况下,您也可以使用@functools.singledispatch来定义泛型函数(由多个函数组成的函数,对不同类型执行相同的操作),而不是使用类型或isinstance。

换句话说,当您有如下代码时,您可能希望使用它:

def do_something(arg):
    if isinstance(arg, int):
        ... # some code specific to processing integers
    if isinstance(arg, str):
        ... # some code specific to processing strings
    if isinstance(arg, list):
        ... # some code specific to processing lists
    ...  # etc

下面是一个工作原理的小示例:

from functools import singledispatch


@singledispatch
def say_type(arg):
    raise NotImplementedError(f"I don't work with {type(arg)}")


@say_type.register
def _(arg: int):
    print(f"{arg} is an integer")


@say_type.register
def _(arg: bool):
    print(f"{arg} is a boolean")
>>> say_type(0)
0 is an integer
>>> say_type(False)
False is a boolean
>>> say_type(dict())
# long error traceback ending with:
NotImplementedError: I don't work with <class 'dict'>

此外,我们可以使用抽象类同时覆盖几种类型:

from collections.abc import Sequence


@say_type.register
def _(arg: Sequence):
    print(f"{arg} is a sequence!")
>>> say_type([0, 1, 2])
[0, 1, 2] is a sequence!
>>> say_type((1, 2, 3))
(1, 2, 3) is a sequence!

type()是比isinstance()更好的解决方案,尤其是对于布尔值:

True和False只是python中表示1和0的关键字。因此

isinstance(True, int)

and

isinstance(False, int)

两者都返回True。两个布尔值都是整数的实例。然而,type()更聪明:

type(True) == int

返回False。