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 inform
According to Python Data Model, everything in Python is an object and every object has an identity, a type and a value.
object
is the base class for all objects, type
is also an object, so it is an instance of object
, and same for object
itself. Also type
is the base class of all object types, so type of object
is type
, and same for type
itself.
This is my understanding, welcome to point out any mistakes.
Answers to all your questions can be found in this book: Python Types and Objects
The most important parts to answer your questions:
Yes, according to the Rule 1 from chapter 1:
"Everything is an object... Any classes that we define are objects, and of course, instances of those classes are objects as well."
object
or type
?From chapter 2:
"These two objects are primitive objects in Python. We might as well have introduced them one at a time but that would lead to the chicken and egg problem - which to introduce first? These two objects are interdependent - they cannot stand on their own since they are defined in terms of each other."
Also Luciano Ramalho in his book "Fluent Python" says that this relation can't be expressed in Python (chapter 21):
"The classes object and type have a unique relationship: object is an instance of type, and type is a subclass of object. This relationship is "magic": it cannot be expressed in Python because either class would have to exist before the other could be defined. The fact that type is an instance of itself is also magical."
So, for your question:
Luciano says that it can't be expressed in Python too.
Many thanks to the author who made this illustration in сhapter 3:
<class 'type'>
is the metaclass of class object
, and every class (including type
) has inherited directly or indirectly from object
.
If you need to find more about metaclasses chack out here https://realpython.com/python-metaclasses/