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


当前回答

使用类型():

>>> a = []
>>> type(a)
<type 'list'>
>>> f = ()
>>> type(f)
<type 'tuple'>

其他回答

使用类型():

>>> a = []
>>> type(a)
<type 'list'>
>>> f = ()
>>> type(f)
<type 'tuple'>

在许多实际情况下,您也可以使用@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!

小心使用isinstance

isinstance(True, bool)
True
>>> isinstance(True, int)
True

但类型

type(True) == bool
True
>>> type(True) == int
False

使用类型()

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

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

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

isinstance(True, int)

and

isinstance(False, int)

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

type(True) == int

返回False。