Difference between type and class

Maric Michaud maric at aristote.info
Thu Jul 31 17:31:44 CEST 2008


Le Thursday 31 July 2008 17:00:51 Nikolaus Rath, vous avez écrit :
> > There are some confusion about the terms here.
> >
> > Classes are instances of type 'type',
>
> Could you please clarify what you mean with 'instance of type X'? I
> guess you mean that 'y is an instance of type X' iif y is constructed
> by instantiating X. Is that correct?
>

Correct, you can verify this with the isinstance builtin :

>>>[1]: isinstance(int(), int)
...[1]: True

>>>[2]: isinstance(int, object)
...[2]: True

>>>[3]: isinstance(int, type)
...[3]: True

>>>[4]: class A(object) : pass
   ...:

>>>[5]: isinstance(A, type)
...[5]: True



> > 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.
>
> But 'int' is an instance of 'type' (the metaclass):
> >>> int.__class__
>
> <type 'type'>
>
> so it should also return '<class int>' if that's the default behavior
> of the 'type' metaclass.
>

The fact that a class is an instance of type, which it is always true, doesn't 
mean its metaclass is "type", it could be any subclass of type :

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

>>>[7]: isinstance(A, type)
...[7]: True

>>>[8]: A.__class__
...[8]: <class '__main__.__metaclass__'>

>>>[9]: issubclass(A.__class__, type)
...[9]: True


> I think that to get '<type int>' one would have to define a new
> metaclass like this:
>
> def type_meta(type):
>     def __repr__(self)
>          return "<type %s>" % self.__name__
>
> and then one should have int.__class__ == type_meta. But obviously
> that's not the case. Why?
>
> Moreover:
> >>> class myint(int):
>
> ...    pass
> ...
>
> >>> myint.__class__ == int.__class__
>
> True
>

*is* comparaison fits better here.

> >>> int
>
> <type 'int'>
>
> >>> myint
>
> <class '__main__.myint'>
>
> despite int and myint having the same metaclass. So if the
> representation is really defined in the 'type' metaclass, then
> type.__repr__ has to make some kind of distinction between int and
> myint, so they cannot be on absolute equal footing.

You're right, type(int) is type, the way it renders differently is a detail of 
its implementation, you can do things with builtin types (written in C) you 
coudn't do in pure python, exactly as you couldn't write recursive types 
like 'object' and 'type'.


-- 
_____________

Maric Michaud



More information about the Python-list mailing list