How to compare type of an object in Python?

后端 未结 14 2432
闹比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 02:13

    You can always use the type(x) == type(y) trick, where y is something with known type.

    # check if x is a regular string
    type(x) == type('')
    # check if x is an integer
    type(x) == type(1)
    # check if x is a NoneType
    type(x) == type(None)
    

    Often there are better ways of doing that, particularly with any recent python. But if you only want to remember one thing, you can remember that.

    In this case, the better ways would be:

    # check if x is a regular string
    type(x) == str
    # check if x is either a regular string or a unicode string
    type(x) in [str, unicode]
    # alternatively:
    isinstance(x, basestring)
    # check if x is an integer
    type(x) == int
    # check if x is a NoneType
    x is None
    

    Note the last case: there is only one instance of NoneType in python, and that is None. You'll see NoneType a lot in exceptions (TypeError: 'NoneType' object is unsubscriptable -- happens to me all the time..) but you'll hardly ever need to refer to it in code.

    Finally, as fengshaun points out, type checking in python is not always a good idea. It's more pythonic to just use the value as though it is the type you expect, and catch (or allow to propagate) exceptions that result from it.

提交回复
热议问题