【问题标题】:How can i check type of object? [duplicate]我如何检查对象的类型? [复制]
【发布时间】:2012-01-12 13:27:43
【问题描述】:

可能重复:
Python - Determine the type of an object?

我想打印“复杂”,但什么也没发生,为什么?如何做到这一点?

>>> c = (5+3j)
>>> type(c)
<type 'complex'>
>>> if type(c) == 'complex': print 'complex'
... 
>>> 

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以使用isinstance:

    if isinstance(c, complex):
    

    来自文档:

    如果 object 参数是 classinfo 参数或其(直接、间接或虚拟)子类的实例,则返回 true。如果 classinfo 是类型对象(新型类)并且 object 是该类型或其(直接、间接或虚拟)子类的对象,则也返回 true。

    【讨论】:

    • 我是从python教程开始的,但是有一些问题在解释之前,谢谢你
    • 在到处使用它之前,您可能希望阅读isinstance() considered harmful
    • 如果这很重要,我会阅读它
    【解决方案2】:
    >>> c = 5+3j
    >>> c
    (5+3j)
    >>> type(c)
    <type 'complex'>
    >>> complex
    <type 'complex'>
    >>> type(c) == complex
    True
    >>> isinstance(c, complex)
    True
    >>>
    

    type(c) == complex 的意思是“这绝对是complex 的一个实例,而不是某个子类”。 isinstance(c, complex) 将包含子类。

    【讨论】:

    • 很高兴知道这一点,谢谢
    【解决方案3】:

    试试if isinstance(c,complex): print 'complex'

    【讨论】:

      猜你喜欢
      • 2016-05-31
      • 2020-04-27
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 2014-07-25
      • 2018-09-03
      • 2011-01-27
      相关资源
      最近更新 更多