I am a little bit confused about the object and type classes in Python 3. Maybe someone can clear up my confusion or provide some additional information.
My current understanding is that every class (except object) inherits from a base class called object. But every class (including object) is also an instance of the class type, which is an instance of itself and object and also inherits from object.
My questions are:
Is there a reason/design decision why
objectis an instance oftypeandtypeinherits fromobject? Has thetype/class of an object also to be an object itself?How can a class (
type) be an instance of itself?Which one is the real base class
objectortype?
I always thoughtobjectwould be the most "fundamental" class, but it seems to be an instance oftype, which is an instance ofobject, which is an instance oftype, ... Where does this recursion end?Is there a possibility to illustrate the relation between the
objectand thetypeclass?
I tried looking up the entries of object and type in the Documentation of the Python Standard Library.
Every class (except object) inherits from object.
>>> for x in object, int, float, str, list, dict:
... print(f'{x.__name__:6}: {x.__bases__}')
...
object: ()
int : (<class 'object'>,)
float : (<class 'object'>,)
str : (<class 'object'>,)
list : (<class 'object'>,)
dict : (<class 'object'>,)
Every class is an instance of the class type.
>>> for x in object, int, float, str, list, dict:
... print(f'{x.__name__:6}: {x.__class__}')
...
object: <class 'type'>
int : <class 'type'>
float : <class 'type'>
str : <class 'type'>
list : <class 'type'>
dict : <class 'type'>
type is an instance of itself.
>>> type.__class__
<class 'type'>
type also inherits from object.
>>> type.__bases__
(<class 'object'>,)
Also
>>> isinstance(object, type)
True
>>> isinstance(type, object)
True
>>> isinstance(type, type)
True
>>> isinstance(object, object)
True
>>> issubclass(type, object)
True
>>> issubclass(object, type)
False
