Difference between type and class

Maric Michaud maric at aristote.info
Thu Jul 31 09:00:27 EDT 2008


Le Thursday 31 July 2008 14:30:19 Nikolaus Rath, vous avez écrit :
> oj <ojeeves at gmail.com> writes:
> > On Jul 31, 11:37 am, Nikolaus Rath <Nikol... at rath.org> wrote:
> >> So why does Python distinguish between e.g. the type 'int' and the
> >> class 'myclass'? Why can't I say that 'int' is a class and 'myclass'
> >> is a type?
> >
> > I might be wrong here, but I think the point is that there is no
> > distinction. A class (lets call it SomeClass for this example) is an
> > object of type 'type', and an instance of a class is an object of type
> > 'SomeClass'.
>
> But there seems to be a distinction:
> >>> class int_class(object):
>
> ...   pass
> ...
>
> >>> int_class
>
> <class '__main__.int_class'>
>
> >>> int
>
> <type 'int'>
>
> why doesn't this print
>
> >>> class int_class(object):
>
> ...   pass
> ...
>
> >>> int_class
>
> <type '__main__.int_class'>
>
> >>> int
>
> <type 'int'>
>
> or
>
> >>> class int_class(object):
>
> ...   pass
> ...
>
> >>> int_class
>
> <class '__main__.int_class'>
>
> >>> int
>
> <class 'int'>
>
> If there is no distinction, how does the Python interpreter know when
> to print 'class' and when to print 'type'?
>

There are some confusion about the terms here.

Classes are instances of type 'type', but types are both instances and 
subclasses of 'type'. 
This recursivity is the base of the object model.

An instance of 'type' is a class (or a new type), but instances of a classes 
are not. 'type' is a metatype in term of OO.

What the <type int> means is that int is not a user type but a builtin type, 
instances of int are not types (or classes) but common objects, so its nature 
is the same as any classes.

The way it prints doesn't matter, it's just the __repr__ of any instance, and 
the default behavior for instances of type is to return '<class XX>', but it 
can be easily customized.

>>>[1]: class A(object) :
   ...:     class __metaclass__(type) :
   ...:         def __repr__(self) : return "<type A>"
   ...:
   ...:

>>>[2]: A
...[2]: <type A>

>>>[3]: type('toto', (object,), {})
...[3]: <class '__main__.toto'>



-- 
_____________

Maric Michaud



More information about the Python-list mailing list