Difference between type and class
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 :
>>>: isinstance(int(), int)
>>>: isinstance(int, object)
>>>: isinstance(int, type)
>>>: class A(object) : pass
>>>: isinstance(A, type)
> > 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 :
>>>: class A(object) :
...: class __metaclass__(type) :
...: def __repr__(self) : return "<type A>"
>>>: isinstance(A, type)
...: <class '__main__.__metaclass__'>
>>>: issubclass(A.__class__, type)
> 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?
> >>> class myint(int):
> ... pass
> >>> myint.__class__ == int.__class__
*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'.
More information about the Python-list