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

后端 未结 7 2350
青春惊慌失措
青春惊慌失措 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:47

    For the real differences, we can find it in code, but I can't find the implement of the default behavior of the isinstance().

    However we can get the similar one abc.__instancecheck__ according to __instancecheck__.

    From above abc.__instancecheck__, after using test below:

    # file tree
    # /test/__init__.py
    # /test/aaa/__init__.py
    # /test/aaa/aa.py
    class b():
    pass
    
    # /test/aaa/a.py
    import sys
    sys.path.append('/test')
    
    from aaa.aa import b
    from aa import b as c
    
    d = b()
    
    print(b, c, d.__class__)
    for i in [b, c, object]:
        print(i, '__subclasses__',  i.__subclasses__())
        print(i, '__mro__', i.__mro__)
        print(i, '__subclasshook__', i.__subclasshook__(d.__class__))
        print(i, '__subclasshook__', i.__subclasshook__(type(d)))
    print(isinstance(d, b))
    print(isinstance(d, c))
    
      
     __subclasses__ []
     __mro__ (, )
     __subclasshook__ NotImplemented
     __subclasshook__ NotImplemented
     __subclasses__ []
     __mro__ (, )
     __subclasshook__ NotImplemented
     __subclasshook__ NotImplemented
     __subclasses__ [..., , ]
     __mro__ (,)
     __subclasshook__ NotImplemented
     __subclasshook__ NotImplemented
    True
    False
    

    I get this conclusion, For type:

    # according to `abc.__instancecheck__`, they are maybe different! I have not found negative one 
    type(INSTANCE) ~= INSTANCE.__class__
    type(CLASS) ~= CLASS.__class__
    

    For isinstance:

    # guess from `abc.__instancecheck__`
    return any(c in cls.__mro__ or c in cls.__subclasses__ or cls.__subclasshook__(c) for c in {INSTANCE.__class__, type(INSTANCE)})
    

    BTW: better not to mix use relative and absolutely import, use absolutely import from project_dir( added by sys.path)

提交回复
热议问题