polymorphism (was Re: Type checking in python?)

Donn Cave donn at u.washington.edu
Wed Jul 26 15:35:36 EDT 2000


Quoth Sean Blakey <sblakey at freei.com>:
...
| The critical point is that in Python, polymorphism depends solely on the
| interface provided, not on any "is-a" relationships.  Instead of
| insisting that your argument must be a string (for example), your code
| should work with any object that exposes the interfaces you need
| (strings, unicode strings, perhaps even a custom class created by
| somebody to emulate Java's StringBuffer, etc.).  Similarly, you don't
| need to verify that your argument is a file, only that it has a read()
| method (or whatever method you use).

Or you can simply expect a read() method.  Don't verify it, don't
support anything else.  The polymorphism is up to the caller.  Examples
of this with the file interface can be found in the library, rfc822 comes
to mind.  I think this is more common than checking for method attributes
and then supporting different interfaces.

In more general terms, you have to pick or create an interface that covers
the important bases.  Often enough it's not worth the trouble, and people
do use alternate input parameters etc.  But where it works out, it could
make the function more flexible and yet simpler, by pushing the support for
different inputs back on the input objects themselves.  Polymorphism.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list