How to compare type of an object in Python?

后端 未结 14 2486
闹比i
闹比i 2020-11-28 01:26

Basically I want to do this:

obj = \'str\'
type ( obj ) == string

I tried:

type ( obj ) == type ( string )
<
14条回答
  •  误落风尘
    2020-11-28 01:54

    Use isinstance(object, type). As above this is easy to use if you know the correct type, e.g.,

    isinstance('dog', str) ## gives bool True
    

    But for more esoteric objects, this can be difficult to use. For example:

    import numpy as np 
    a = np.array([1,2,3]) 
    isinstance(a,np.array) ## breaks
    

    but you can do this trick:

    y = type(np.array([1]))
    isinstance(a,y) ## gives bool True 
    

    So I recommend instantiating a variable (y in this case) with a type of the object you want to check (e.g., type(np.array())), then using isinstance.

提交回复
热议问题