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

后端 未结 7 2345
青春惊慌失措
青春惊慌失措 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 06:58

    Here's an example where isinstance achieves something that type cannot:

    class Vehicle:
        pass
    
    class Truck(Vehicle):
        pass
    

    in this case, a truck object is a Vehicle, but you'll get this:

    isinstance(Vehicle(), Vehicle)  # returns True
    type(Vehicle()) == Vehicle      # returns True
    isinstance(Truck(), Vehicle)    # returns True
    type(Truck()) == Vehicle        # returns False, and this probably won't be what you want.
    

    In other words, isinstance is true for subclasses, too.

    Also see: How to compare type of an object in Python?

提交回复
热议问题