Rishabh Kumar
Rishabh Kumar

Reputation: 101

what is the difference between type class and object class in python

I am learning about metaclass and I see that every class is a subclass of type class in python but sometimes I see people are using object class but object class is also a subclass of type class then what is the difference between them?

enter image description here

Upvotes: 4

Views: 3779

Answers (1)

jsbueno
jsbueno

Reputation: 110591

object is not a subclass of type: it is an instance of type.

object, the class, is the root of all class hierarchy in Python - however as everything in Python is an instance, it has to have a "class" that when properly instantiated with the proper parameters results in it.

As it is an obvious "chicken and egg" paradox, after all, the class type itself must inherit from object, that part of the class hierarchy is hand-wired in loop: it would be impossible to replicate the same relationships in pure Python code.

And finally: a class being an instance of a metaclass is not the same as inheriting, or being a subclass of that metaclass: inheritance hierarchy is one thing, the metaclass, which is used to construct each class itself, is another, ortogonal thing.

So, to recap: all classes in Python are themselves instances of a "metaclass" - and the default metaclass is type. All classes in Python also inherit from object - and that includes type. The class object itself must also be an instance of type, and that relationship is hardcoded in the Python runtime source-code (which is written in C in the case of cPython)

Upvotes: 10

Related Questions