How to compare type of an object in Python?

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

    isinstance works:

    if isinstance(obj, MyClass): do_foo(obj)
    

    but, keep in mind: if it looks like a duck, and if it sounds like a duck, it is a duck.

    EDIT: For the None type, you can simply do:

    if obj is None: obj = MyClass()
    

提交回复
热议问题