Reputation: 4469
This site lists type()
as among the built-in functions in Python. However, when I check it seems to be of type 'type':
>>> type(dir)
<type 'builtin_function_or_method'>
>>> type(id)
<type 'builtin_function_or_method'>
>>> type(abs)
<type 'builtin_function_or_method'>
>>> type(type)
<type 'type'>
To me, it seems that type()
is a built-in function which returns the type of the argument. I'm trying to verify this with:
>>> a = type(type)
>>> type(a)
<type 'type'>
>>> type(1)
<type 'int'>
>>> type(type(1))
<type 'type'>
What am I missing here? Is type()
just a constructor for the type
class from which all other objects inherit?
Upvotes: 3
Views: 123
Reputation: 184071
Yes. type()
is both a function-like object that returns the type of an object, and also a class that serves as the base metaclass for all classes (not the base class, but close). It distinguishes its two functions by the number of arguments passed to it. One argument, it returns the type of that argument. Three arguments, and it returns a class built from those arguments.
(A metaclass is the class of a class. Just as regular objects are instances of some class, a class is an instance of a metaclass.)
It's this way for historical reasons. Originally, it was just a function that got the type of the object. In Python 2.2, when built-in types and user-defined classes were unified, it became the base metaclass. However, for backward compatibility, the functionality of the old type()
was retained as part of the type
class.
Upvotes: 5