Difference between type and class
Terry Reedy
tjreedy at udel.edu
Tue Aug 5 15:03:27 EDT 2008
Gabriel Genellina wrote:
A decade ago, in 1.x, 'types' were built-in classes. They were
instances of class 'type'. 'Classes' were user-defined classes. They
were instances of (built-in) class 'classob'. User classes had the same
status as instances of any other built-in class. They could only
inherit from other instances of 'UserClass'. Instances of user classes
were actually instances of built-in class 'instance'. They could not be
instances of the user class because user classes were, in a sense, not
really classes, just instances of 'classob' that emulated 'real' classes.
>>> class C(): pass
...
>>> c=C()
>>> type(C)
<type 'classobj'>
>>> type(c)
<type 'instance'>
Many users found the distinction between built-in classes and user
classes confusing and limiting. Users wanted to be able to use built-in
classes as base classes for user classes. So in 2.2 'object' was added
as the base-class for all built-in classes and user-classes with
'object' in the base-class tree became instances of type (or of some
other meta-class derived from type) instead of classob. But the
representation of new-style classes matched that of old-style classes
rather than that of the other instances of 'type' that happened to be
built in.
In 3.0, built-in classes 'classob' and 'instance' are gone, along with
the confusion of having two categories of user classes along with an
apparently separate category of built-in classes. User-classes are real
classes on a par with C-coded classes.
>>> class C(): pass # 3.0, in 2.x, class c(object)
>>> c=C()
>>> type(C)
<class 'type'> # same as
>> type(int)
<class 'type'>
>>> type(c)
<class '__main__.C'>
> If it helps you to understand the issue, in Python 3.0 that
> difference is gone - the word "class" is used on both cases. See
> http://bugs.python.org/issue2565
The only visible difference now (in 3.0) is that C-coded built-in
classes that are present as startup and which do not live in any
particular module do not have a module name as part of their
representation. Imported C-coded classes show no difference (and
indeed, in other implementations, they might be coded in Python or ??
rather than C).
>>> int
<class 'int'>
>>> c
<class '__main__.c'>
>>> import itertools as i
>>> i.product
<class 'itertools.product'>
I believe this should mean that if one write a module in Python and
later rewrites part of it in C for speed, with identical API, the change
of implementation will otherwise be transparent to user code and users,
as it ought to be.
Terry Jan Reedy
More information about the Python-list
mailing list