First, I'm sorry if I'm asking something dumb, because I'm new to Python...
I was reading http://docs.python.org/3.1/reference/datamodel.html#objects-values-and-types and saw that phrase:
The type() function returns an object’s type (which is an object itself)
Of course, I decided to check this:
>>> def someFunction(x):
... return x * x
...
>>> type(someFunction)
<class 'function'>
>>> type(type)
<class 'type'>
So, looks like functions have the function type, but then why type function has a different type if it is a function? Or the docs are lying and it's not really a function?
Yes, type is a function, but it is implemented in C.
It also has to be it's own type, otherwise you could not do:
>>> def foo(): pass
...
>>> type(foo)
<type 'function'>
>>> type(type)
<type 'type'>
>>> isinstance(type(foo), type)
True
e.g. you could not test if a type is a type, if type's type was not type but function. With me still?
Technically speaking, type is a callable, and has two related roles to play. It is a metaclass (a class factory) and the base for all types in Python, and when called it produces a type instance (<type 'function'> is an instance of the type type).
The same applies to all types (including classes); call them and they produce a new instance of the given type.
type is a built-in function, i.e. object of type that you can call as function. You can call it with one argument to get the type of an object. But there is also another use case.type is a metaclass, this means it is a type itself and can create classes (which are objects too).type is function. You can call it with three arguments to create a class.type is basic built-in metaclass. So it is a base of anything in Python. Because type is on top of hierarchy of types, type(type) returns type, i.e. type is type of itself.You also may wonder:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With