【问题标题】:How to know the type of a object in a simple way?如何以简单的方式知道对象的类型?
【发布时间】:2014-09-30 03:24:28
【问题描述】:

我总是写这样的代码:

str(type(a)).find('int') != -1

或者

t = str(type(a)).split("'")[1]

有什么简单的方法吗?

【问题讨论】:

    标签: python object object-type


    【解决方案1】:

    你好像在问isinstance()

    >>> a = 1
    >>> isinstance(a, int)
    True
    >>> s = "test"
    >>> isinstance(s, str)
    True
    

    说到第二个例子(字符串类型),需要注意的是有一个basestring类型:

    【讨论】:

      【解决方案2】:
      isinstance(a, int)
      

      例子:

      In [4]: a = 5
      
      In [5]: isinstance(a, int)
      Out[5]: True
      

      【讨论】:

        猜你喜欢
        • 2022-01-20
        • 2010-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-02
        • 1970-01-01
        相关资源
        最近更新 更多