How do you explain isinstance(Hello,object)
returns True whilst issubclass(Hello,object)
returns False?
>>> class Hello: pass
and
>>> isinstance(Hello,object) True >>> issubclass(Hello,object) False >>> a = Hello() >>> isinstance(a,object) True
isinstance() and issubclass() The isinstance() method checks whether an object is an instance of a class whereas issubclass() method asks whether one class is a subclass of another class (or other classes).
isinstance() checks whether or not the object is an instance or subclass of the classinfo. Whereas, issubclass() only check whether it is a subclass of classinfo or not (not check for object relation).
Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.
The isinstance() function is faster than the type function. We can compare both their performance by using the timeit library. As you can see, the isinstance() function is 30 times faster than type() function.
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
It's because you are using old-style classes so it doesn't derive from object
. Try this instead:
class Hello(object): pass >>> issubclass(Hello,object) True
Old-style classes are deprecated and you shouldn't use them any more.
In Python 3.x all classes are new-style and writing (object)
is no longer required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With