type vs. class

Alex Martelli aleaxit at yahoo.com
Mon Dec 11 04:35:41 EST 2000


"Greg Jorgensen" <gregj at pobox.com> wrote in message
news:uE_Y5.133498$U46.4497870 at news1.sttls1.wa.home.com...
> "Thomas Thiele" <tnt-audio at t-online.de> wrote:
>
> > >>> class X:
> > pass
> >
> > >>> x = X()
> > >>> type(x)
> > <type 'instance'>
> >
> > How can I realize that I will not get type 'instance' but type 'X'? I
> > have different classes, more than one, and I want to check out which
> > class it is.  Are all classes type instance?
>
> In Python a class does not create a new type. All classes are of type
> ClassType, and all class instances are of type InstanceType.
>
> The built-in function isinstance(object, class) may be what you need:

Perfectly true -- isinstance() is often more useful than type()!

However, to satisfy Thomas's request as he posed it...: when x is an
instance of some class, you can learn WHICH class it's an instance
of, through x's __class__ attribute (you can get the NAME of the
class as a string, through the class-object's own __name__ attribute):

>>> class X:
...   pass
...
>>> x=X()
>>> x.__class__
<class __main__.X at 007F76CC>
>>> x.__class__.__name__
'X'
>>>


Alex







More information about the Python-list mailing list