type() does two things:
- with a single argument, it returns the actual type of an object;
- with three arguments, it creates new types.
For example, type(42)
returns int, and type([]) returns list. Not the *strings* "int" and "list", but the actual int object and list object.
py> x = 42
py> type(x)("23")
23
The three argument form of type() creates new types, also known as classes. The class statement is just syntactic sugar, under the hood it calls type.
(Note: in Python 2 there is a slight complication due to the existence of so-called "old-style classes", also known as "classic classes". They are a bit of a special case, but otherwise don't really make any difference to what I'm saying.)
For example, the following:
class Spam(object):
a = 42
def method(self, x):
return self.a + x
is syntactic sugar for the much longer:
def method(self, x):
return self.a + x
d = {'method': method, 'a': 42}
Spam = type('Spam', (object,), d)
del d, method
(more or less, there may be slight differences).