2

I'm currently learning python OOP model and have been told

type itself derives from object, and object derives from type

I understand that object is the default superclass of every class in python 3.x, and type class is used to created classes (i.e. class object). object and type together (somehow) forms the bases of python OOP, but I am still confused as ever about the statement above.

Could someone provide a detailed explanation on the relationship between object and type, and the roles they play in python OOP. Thanks

Thor
  • 9,638
  • 15
  • 62
  • 137
  • 3
    Possible duplicate of [What are metaclasses in Python?](https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python) – Klaus D. Oct 12 '18 at 03:26
  • 1
    Just because this question has an answer that relates to metaclasses, that does not mean that this question is a duplicate. – Daenyth Oct 13 '18 at 02:12

1 Answers1

5

We need to distinguish subclassing from instantiation. The exact rules can vary with the language, but in Python 3.x--

All classes are subclasses of object (well, except for object itself). object is the root of the class hierarchy.

The type class is a subclass of object.

All objects are instances of a class.

Classes are themselves objects. (This is not true in every language.)

Class objects, being objects, are instances of a class--class objects are instances of the class type (the default metaclass).

Yes, type is a class and an object, and it is an instance of type. type has class type.

Yes, object is a class and an object, and it is an instance of type. object has class type.

You can see the class of an object by using .__class__ or type() on it. You can see the superclasses of a class by using .__mro__ (method resolution order) on it.

>>> type(object)
<class 'type'>
>>> type(type)
<class 'type'>
>>> object.__mro__
(<class 'object'>,)
>>> type.__mro__
(<class 'type'>, <class 'object'>)
gilch
  • 10,813
  • 1
  • 23
  • 28