Re: Difference between type and class



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. The following example should clarify matters:

class A:
def bar(self):
print "A"

class B:
def bar(self):
print "B"

class C:
def bla(self):
print "C"

def foo(x):
x.bar()

you can call foo with instances of both A and B, because both classes share a common type, namely the type that has a `bar' method), but not with an instance of C because it has no method `bar'. Btw, this example shows the use of duck typing (http://en.wikipedia.org/wiki/Duck_typing).

HTH,
Thomas.
.



Relevant Pages