Polymorphism
holger krekel
pyth at devel.trillke.net
Mon Aug 5 19:30:21 EDT 2002
Carlos Moreira wrote:
> How Python implement Polymorphism?
>
> []'s
With python you mostly care what you can *do* to an
object not which exact type it has.
So take e.g. the tokenize module which has a method
def tokenize(readline, tokeneater=printtoken):
...
which takes a function 'readline' and calls it.
You only need to provide an object which can be
called and provides a string. So
tokenize.tokenize(['','i+5'].pop)
does the job. First called it returns 'i+5' and
second time it returns the empty string which indicates
end of input. There was no need to assert some base class ...
However, it's easy enough to dispatch on the type
of an object, e.g.
dispatch_dict = {
int : HandleInt,
str : HandleStr,
list : HandleList
}
def polymorphic_func(arg, *otherargs):
return dispatch_dict(type(arg)) (*otherargs)
But often you might improve your design by focusing
more on what you want to *do* with your objects
rather than asserting exact types.
Besides, i think that implementing polymorphism more or
less involves a mechanism for static type declaration.
And this should only happen very carefully if at all.
HTH,
holger
More information about the Python-list
mailing list