0

What is the relation between class type and specific types?

I thought that specific types were subclasses of type, but:

>>> type
<class 'type'>
>>> import builtins
>>> builtins.issubclass(type, object)
True
>>> builtins.issubclass(int, type)
False

Thanks.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Tim
  • 1
  • 141
  • 372
  • 590

1 Answers1

4

I thought that specific types were subclasses of type

They aren't. Every class is an instance of type; type acts as the class for classes. isinstance(class, type) returns True while issubclass correctly returns False.

A case where issubclass returns True is with custom meta-classes (class of classes) that actually inherit from type. For example, take EnumMeta:

>>> from enum import EnumMeta
>>> issubclass(EnumMeta, type)

This is True because EnumMeta has type as a base class (inherits from it):

>>> EnumMeta.__bases__
(type,)

if you looked its source up you'd see it's defined as class EnumMeta(type): ....


issubclass(type, object) returns True for everything because every single thing in Python is an object (meaning everything inherits from object).

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • Thanks. What class is `type` an object of? – Tim Jun 29 '17 at 21:15
  • @Tim `type` is an instance of itself :-) (see `isinstance(type, type)`). This does get confusing and explaining it isn't sufficient in a single comment; you can take a look at [this nice article](http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html) that explains these relationships. – Dimitris Fasarakis Hilliard Jun 29 '17 at 21:21