type vs. class

Greg Jorgensen gregj at pobox.com
Mon Dec 11 07:39:22 CET 2000


"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:

>>> class A: pass
>>> a = A()
>>> isinstance(a, A)
1

isinstance returns true if the object is a member of the specified class or
any class derived from the specified class:

>>> class B(A): pass
>>> b = B()
>>> isinstance(b, A)
1
>>> isinstance(a, B)
0

The built-in function issubclass(A, B) may be useful to you:

>>> issubclass(B, A)
1

isinstance can also be used with the built-in types:

>>> import types
>>> isinstance(3, types.IntType)
1

--
Greg Jorgensen
Deschooling Society
Portland, Oregon, USA
gregj at pobox.com





More information about the Python-list mailing list