4

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

5
  • 1
    Does this answer your question? Class vs. Type in Python Commented Mar 5, 2021 at 20:59
  • 1
    object is the base class of everything in Python. That is what it means when people say "everything is an object*. So it is always true if you do isinstance(x, object) for any x. Explicitly inherting from object is not necessary, that will happen by default, so class Foo(object): ... is equivalent to class Foo: ... Commented Mar 5, 2021 at 20:59
  • @mkrieger1 not exactly... that is discussing old vs new style classes. In Python 3, all classes are instances of type. And all instance, (i.e. everything) is an instance of object. This wasn't always the case. Commented Mar 5, 2021 at 21:01
  • You may notice, there is a circularity: isinstance(object, type) and isinstance(type, object) are both true! And perhaps even more curiously, type(type) is type, and for that matter, isinstance(object, object) is true! Read more about this here: stackoverflow.com/questions/55775218/… Commented Mar 5, 2021 at 21:05
  • "every class is a subclass of type class" - wrong - "but object class is also a subclass of type class" - no it's not. Commented Mar 5, 2021 at 22:14

1 Answer 1

10

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Great... I really wanted to hear this sentence : "it would be impossible to replicate the same relationships in pure Python code."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.