Is type the super class of all classes in Python?

python, superclass

Solution

`type` isn't the superclass of all classes. It is the type of all classes (that don't have a custom metaclass). Note the difference:

>>> isinstance(1, int)
True
>>> isinstance(1, type)
False
>>> isinstance(int, type)
True

The number 1 is not an instance of type. Rather, the `int` type itself is an instance of `type`.

Edit:

These examples may help you:

>>> isinstance(1, int)
True
>>> issubclass(1, int)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    issubclass(1, int)
TypeError: issubclass() arg 1 must be a class
>>> class Foo(object):
...     pass
>>> isinstance(Foo, type)
True
>>> issubclass(Foo, type)
False # Note the difference from the previous!
>>> isinstance(Foo, object)
True
>>> issubclass(Foo, object)
True
>>> isinstance(int, type)
True
>>> issubclass(int, type)
False # Note the difference from the previous!

From your comment, it seems you are misunderstanding how inheritance works. There is a difference between being an instance of a type and being a subclass (or subtype) of a type. If an object X is an instance of type A, and type A is a subclass of type B, then X is also an instance of B. But if type A is an instance of type B, then X is not an instance of B. In other words, subclasshood is transitive, but instancehood is not.

A real world analogy would be between something like "species" and "homo sapiens". You could say that "species" is a type and "homo sapiens" is an instance of that type; in other words, "homo sapiens" is a particular species. But "homo sapiens" is also a type, and an individual human is an instance of that type. For instance, Barack Obama (to pick a well-known example) is an instance of "homo sapiens"; that is, he is a particular homo sapiens. But Barack Obama is not an instance of species; he is not a species himself.

The relationship between `type`, `int`, and the number 1 is similar. The number 1 is an instance of `int`, and `int` is an instance of `type`, but that doesn't mean that 1 is an instance of type.

Problem

Given that `type` is the superclass of all classes, why `isinstance(1, type)` is `False`? Am I understanding the concept wrong?

Original source