【问题标题】:Check whether the type of a variable is a specific type in Python检查变量的类型是否是Python中的特定类型
【发布时间】:2013-03-03 15:06:54
【问题描述】:

我想检查变量的类型是否是 Python 中的特定类型。例如-我想检查 var x 是否为 int。

>>x=10
>>type(x)
<type 'int'>

但是我如何比较它们的类型。我试过这个,但它似乎不起作用。

if type(10)== "<type 'int'>":
    print 'yes'

我该怎么做?

【问题讨论】:

  • 值得注意的是,显式检查 - 并分支 - 变量类型被广泛认为是非 Pythonic,因为它直接违反了鸭子类型:en.wikipedia.org/wiki/Duck_typing

标签: python


【解决方案1】:

使用isinstance() function 测试特定类型:

isinstance(x, int)

isinstance() 采用单一类型或类型元组进行测试:

isinstance(x, (float, complex, int))

例如,将测试一系列不同的数字类型。

【讨论】:

  • 值得注意的是,您也可以使用元组而不是类型,然后如果变量是元组中给定的任何类型,它将返回 True,例如:isinstance(x, (int, float, decimal)) 将返回如果x 是整数、浮点数或小数,则为真。
  • @InbarRose:确实;我总是以complex 为例。 :-)
【解决方案2】:

你的例子可以写成:

if type(10) is int: # "==" instead of "is" would also work.
    print 'yes'

但请注意,它可能不会完全按照您的意愿进行操作,例如,如果您写了10L 或大于sys.maxint 的数字,而不仅仅是10,则不会打印yes,因为long (这将是这样一个数字的类型)不是int

正如 Martijn 已经建议的那样,另一种方法是使用 isinstance() 内置函数,如下所示:

if isinstance(type(10), int):
    print 'yes'

insinstance(instance, Type) 不仅在type(instance) is Type 的情况下返回True,而且在实例的类型派生自Type 的情况下也返回True。因此,由于boolint 的子类,这也适用于TrueFalse

但通常最好不要检查特定类型,而是检查您需要的功能。也就是说,如果您的代码无法处理该类型,它会在尝试对该类型执行不受支持的操作时自动抛出异常。

但是,如果您需要处理例如整数和浮点数不同,您可能需要检查 isinstance(var, numbers.Integral)(需要 import numbers),如果 var 的类型为 intlongbool 或任何用户,则其计算结果为 True - 从此类派生的定义类型。请参阅the standard type hierarchy 和 [numbers 模块] 上的 Python 文档

【讨论】:

    【解决方案3】:

    您可以使用以下方式:

    >>> isinstance('ss', str)
    True
    >>> type('ss')
    <class 'str'>
    >>> type('ss') == str
    True
    >>> 
    

    int -> 整数

    float -> 浮点值

    列表 -> 列表

    元组 -> 元组

    dict -> 字典

    对于类来说有点不同: 旧类型类:

    >>> # We want to check if cls is a class
    >>> class A:
            pass
    >>> type(A)
    <type 'classobj'>
    >>> type(A) == type(cls)  # This should tell us
    

    新类型类:

    >>> # We want to check if cls is a class
    >>> class B(object):
            pass
    >>> type(B)
    <type 'type'>
    >>> type(cls) == type(B)  # This should tell us
    
    
    >>> #OR
    >>> type(cls) == type # This should tell us
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 2014-07-19
      • 2011-10-15
      • 1970-01-01
      • 2015-05-24
      • 2021-07-13
      • 2023-01-24
      相关资源
      最近更新 更多