[Pyrex] Type() on Pyrex classes
Greg Ewing
greg at cosc.canterbury.ac.nz
Wed May 21 07:58:00 CEST 2003
jkoshy at FreeBSD.ORG (Joseph Koshy) wrote:
> What *is* the difference between a 'type' and a 'class' in Python?
In the old days, a 'type' was a built-in object (implemented in C) and
a 'class' was a user-defined class (created with the Python 'class'
statement).
This is changing, and we now have built-in types that can be
subclassed in Python, such subclasses being know as a "new-style
classes". But for backwards compatibility, the original user-defined
class type is still around, instances of which are known as "old-style
classes".
New-style classes are pretty much indistinguishable from built-in
types, and both print out as "<type 'foo'>". Old-style classes, on the
other hand, print out as "<class 'foo'>".
> cdef class Foo:
> pass
In Pyrex, this defines a new built-in type that is subclassable.
> class Bar:
> pass
This creates an old-style class, because it doesn't inherit from any
built-in types or new-style classes.
> class Buzz(Foo):
> pass
This creates a new-style class, because it inherits from Foo, which is
a built-in type.
For the most part, you don't need to be concerned about the difference
between old-style and new-style classes, except for a few things like
property() that only work with new-style classes.
> I'd like my module to export symbols 'FooType', 'BarType' and 'BuzzType'
> which reference the appropriate type objects.
There's no need for this. In the case of built-in types and new-style
classes, the class *is* the type object, i.e. Foo and Buzz are already
type objects; in the case of old-style classes, there's no type object
that's of any use to you.
You shouldn't be using type(x) == FooType to test the types of things
anyway -- that's an obsolete and incorrect idiom now that we have
subclassable types. Use isinstance() instead, e.g.
isinstance(x, Foo)
will test whether x is a Foo or any of its subclasses. It will also
work correctly regardless of whether Foo is an old-style or new-style
class.
Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury, | A citizen of NewZealandCorp, a |
Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. |
greg at cosc.canterbury.ac.nz +--------------------------------------+
More information about the Pyrex
mailing list