零零乙 2010-02-08 21:37 采纳率: 33.3%
浏览 184
已采纳

确定对象的类型?

Is there a simple way to determine if a variable is a list, dictionary, or something else? I am getting an object back that may be either type and I need to be able to tell the difference.

转载于:https://stackoverflow.com/questions/2225038/determine-the-type-of-an-object

  • 写回答

8条回答 默认 最新

  • hurriedly% 2010-02-08 21:40
    关注

    To get the type of an object, you can use the built-in type() function. Passing an object as the only parameter will return the type object of that object:

    >>> type([]) is list
    True
    >>> type({}) is dict
    True
    >>> type('') is str
    True
    >>> type(0) is int
    True
    >>> type({})
    <type 'dict'>
    >>> type([])
    <type 'list'>
    

    This of course also works for custom types:

    >>> class Test1 (object):
            pass
    >>> class Test2 (Test1):
            pass
    >>> a = Test1()
    >>> b = Test2()
    >>> type(a) is Test1
    True
    >>> type(b) is Test2
    True
    

    Note that type() will only return the immediate type of the object, but won’t be able to tell you about type inheritance.

    >>> type(b) is Test1
    False
    

    To cover that, you should use the isinstance function. This of course also works for built-in types:

    >>> isinstance(b, Test1)
    True
    >>> isinstance(b, Test2)
    True
    >>> isinstance(a, Test1)
    True
    >>> isinstance(a, Test2)
    False
    >>> isinstance([], list)
    True
    >>> isinstance({}, dict)
    True
    

    isinstance() is usually the preferred way to ensure the type of an object because it will also accept derived types. So unless you actually need the type object (for whatever reason), using isinstance() is preferred over type().

    The second parameter of isinstance() also accepts a tuple of types, so it’s possible to check for multiple types at once. isinstance will then return true, if the object is of any of those types:

    >>> isinstance([], (tuple, list, set))
    True
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真