Difference between type and class
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Thu Jul 31 18:40:41 EDT 2008
On Thu, 31 Jul 2008 13:32:39 +0200, Thomas Troeger wrote:
>> Can someone explain to me the difference between a type and a class?
>
> If your confusion is of a more general nature I suggest reading the
> introduction of `Design Patterns' (ISBN-10: 0201633612), under
> `Specifying Object Interfaces'.
>
> In short: A type denotes a certain interface, i.e. a set of signatures,
> whereas a class tells us how an object is implemented (like a
> blueprint). A class can have many types if it implements all their
> interfaces, and different classes can have the same type if they share a
> common interface.
I fear you're introducing a rather complicated answer for a simple
question. In Python, the simple answer is that built-in objects like int,
float, str etc. are referred to as "types", and custom objects created
using the class keyword are referred to as "classes". This is a
historical distinction that will disappear in time.
We can see that types and classes already have the same type in Python:
>>> class Parrot(object):
... pass
...
>>> type(Parrot)
<type 'type'>
>>> type(str)
<type 'type'>
> The following example should clarify matters:
>
> class A:
> def bar(self):
> print "A"
Alas, you've chosen the worst-possible example to "clarify" matters,
because old-style classic classes are *not* unified with types, and will
disappear in the future:
>>> class Old: # don't inherit from object
... pass
...
>>> type(Old)
<type 'classobj'>
So, to the Original Poster:
In Python, new-style classes and types are the same, but it is
traditional to refer to customer objects as "class" and built-in objects
as "types". Old-style classes are different, but you are discouraged from
using old-style classes unless you have a specific reason for needing
them (e.g. backwards compatibility).
--
Steven
More information about the Python-list
mailing list