Re: Difference between type and class
- From: Maric Michaud <maric@xxxxxxxxxxxxx>
- Date: Thu, 31 Jul 2008 17:31:44 +0200
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]: True[1]: isinstance(int(), int)
...[2]: True[2]: isinstance(int, object)
...[3]: True[3]: isinstance(int, type)
...:[4]: class A(object) : pass
...[5]: True[5]: 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 __metaclass__(type) :[6]: class A(object) :
...: def __repr__(self) : return "<type A>"
...:
...:
...[7]: True[7]: isinstance(A, type)
...[8]: <class '__main__.__metaclass__'>[8]: A.__class__
...[9]: True[9]: 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?
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
.
- References:
- Difference between type and class
- From: Nikolaus Rath
- Re: Difference between type and class
- From: Maric Michaud
- Difference between type and class
- Prev by Date: Re: undo a dictionary
- Next by Date: Re: Newbie Python questions
- Previous by thread: Re: Difference between type and class
- Next by thread: Re: Difference between type and class
- Index(es):
Relevant Pages
|