Determine the type of an object?

后端 未结 13 2187
余生分开走
余生分开走 2020-11-22 05:50

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

13条回答
  •  难免孤独
    2020-11-22 06:21

    On instances of object you also have the:

    __class__
    

    attribute. Here is a sample taken from Python 3.3 console

    >>> str = "str"
    >>> str.__class__
    
    >>> i = 2
    >>> i.__class__
    
    >>> class Test():
    ...     pass
    ...
    >>> a = Test()
    >>> a.__class__
    
    

    Beware that in python 3.x and in New-Style classes (aviable optionally from Python 2.6) class and type have been merged and this can sometime lead to unexpected results. Mainly for this reason my favorite way of testing types/classes is to the isinstance built in function.

提交回复
热议问题