Reputation: 8128
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?
Upvotes: 4
Views: 225
Reputation: 1
You should understand some concepts first:
class XYZ: pass print(type(XYZ))
output: <class 'type'>
Upvotes: 0
Reputation: 5481
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:
Upvotes: 3
Reputation: 5890
type
is a class, that deals with class objects. Invoking it with an object is only one way to use it. You can also use it to create meta classes.
For example
>>> MyMetaClass = type("MyMetaClass", (object,), {'foo': 'bar'})
>>> newmeta = MyMetaClass()
>>> newmeta.foo
'bar'
>>> type(MyMetaClass)
<type 'type'>
>>> type(newmeta)
<class '__main__.MyMetaClass'>
Upvotes: 0
Reputation: 1124318
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.
Upvotes: 11