isinstance() and issubclass() return conflicting results

后端 未结 4 1952
既然无缘
既然无缘 2020-12-16 10:39
>>> class Hello:
    pass

and

>>> isinstance(Hello,object)
True
>>> issubclass(Hello,object)
False
>         


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 11:23

    The accepted answer is correct, but seems to miss an important point. The built-in functions isinstance and issubclass ask two different questions.

    isinstance(object, classinfo) asks whether an object is an instance of a class (or a tuple of classes).

    issubclass(class, classinfo) asks whether one class is a subclass of another class (or other classes).

    In either method, classinfo can be a “class, type, or tuple of classes, types, and such tuples.”

    Since classes are themselves objects, isinstance applies just fine. We can also ask whether a class is a subclass of another class. But, we shouldn't necessarily expect the same answer from both questions.

    class Foo(object):
        pass
    
    class Bar(Foo):
        pass
    
    issubclass(Bar, Foo)
    #>True
    isinstance(Bar, Foo)
    #>False
    

    Bar is a subclass of Foo, not an instance of it. Bar is an instance of type which is a subclass of object, therefore the class Bar is an instance of object.

    isinstance(Bar, type)
    #>True
    issubclass(type, object)
    #>True
    isinstance(Bar, object)
    #>True
    

提交回复
热议问题