What are the differences between type() and isinstance()?

后端 未结 7 2347
青春惊慌失措
青春惊慌失措 2020-11-21 06:06

What are the differences between these two code fragments?

Using type():

import types

if type(a) is types.DictType:
    do_something(         


        
相关标签:
7条回答
  • 2020-11-21 07:07

    A practical usage difference is how they handle booleans:

    True and False are just keywords that mean 1 and 0 in python. Thus,

    isinstance(True, int)
    

    and

    isinstance(False, int)
    

    both return True. Both booleans are an instance of an integer. type(), however, is more clever:

    type(True) == int
    

    returns False.

    0 讨论(0)
提交回复
热议问题