How to compare type of an object in Python?

后端 未结 14 2487
闹比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:52

    First, avoid all type comparisons. They're very, very rarely necessary. Sometimes, they help to check parameter types in a function -- even that's rare. Wrong type data will raise an exception, and that's all you'll ever need.

    All of the basic conversion functions will map as equal to the type function.

    type(9) is int
    type(2.5) is float
    type('x') is str
    type(u'x') is unicode
    type(2+3j) is complex
    

    There are a few other cases.

    isinstance( 'x', basestring )
    isinstance( u'u', basestring )
    isinstance( 9, int )
    isinstance( 2.5, float )
    isinstance( (2+3j), complex )
    

    None, BTW, never needs any of this kind of type checking. None is the only instance of NoneType. The None object is a Singleton. Just check for None

    variable is None
    

    BTW, do not use the above in general. Use ordinary exceptions and Python's own natural polymorphism.

提交回复
热议问题