Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is 'type' in Python?

Tags:

python

>>> type(type)
<type 'type'>

I expect the type of type to be a function since it's used to return the type of the argument. Does this mean a type can accept arguments? Is type something unusual/special?

like image 360
Mike Avatar asked Sep 18 '26 16:09

Mike


2 Answers

type is a metaclass: a class whose instances are also classes. The type of any other builtin class will also be type - eg:

>>> type(object)
<class 'type'>
>>> type(list)
<class 'type'>

Indeed, every (new-style) class will also be an instance of type, although if it is defined with a custom metaclass, type(my_class) will be that metaclass. But since every metaclass is required to inherit from type, you will have, for any class:

>>> isinstance(my_class, type)
True
like image 200
lvc Avatar answered Sep 20 '26 06:09

lvc


Classes are objects. All objects are instances of a class. So since a class is an object, it is an instance of some class. The class that a class is an instance of is named type. It is the base metaclass.

Originally type() was just a function that returned an object's class. In Python 2.2, user-defined classes and built-in types were unified, and type became a class. For backward compatibility, it still behaves like the old type() function when called with one argument.

like image 32
kindall Avatar answered Sep 20 '26 04:09

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!