polymorphism (was Re: Type checking in python?)

Sean Blakey sblakey at freei.com
Wed Jul 26 14:28:48 EDT 2000


On Wed, Jul 26, 2000 at 03:14:01PM +0200, Oivvio Polite wrote:
> Hi all.
> 
> I'm building a class with a uniform interface and I'm trying to come to
> terms with polymorphism in python.
> 
> For instance I want the constructor to take either a filename, a file object
> or a database connection object.
> In C++ this would be done using three different constructors. (I'm not quite
> sure about this, cause I don't know C++ :-)
> But how should one do it in python.
> 
> My first idea was something like this:
> 
> class myclass:
>     def __init__:(self, arg):
>         if type(arg) == types.StringType:
>             #check if that's a filename and do the right initialization.
>         elif type(arg) == types.FileType:
>             #do the initialization in an other way
>         # and so on
> 

In my experience, using the type() builtin is more pain than it's worth.
I like the scheme proposed by Alex Martelli, except that I would have
used

    def __init__(filename='', fileobject=None, dbconn=None):

instead (personal style I guess.  I like to keep strings as strings,
even if they are "false" strings).

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).

Alternately, to keep closer to the style of your original:

class myclass:
    def __init__(self, arg):
        try:
            if os.path.isfile(arg):
                # Do proper string initialization here
        except TypeError: #not a string
            try:
                data = arg.read()
                # File intialization
            except (AttributeError, TypeError):     #Not a file
                # DB Connection initialization



-- 
Sean Blakey, sblakey at freei.com
Software Developer, FreeInternet.com
(253)796-6500x1025
Computers are unreliable, but humans are even more unreliable.
Any system which depends on human reliability is unreliable.
		-- Gilb




More information about the Python-list mailing list