Re: polymorphism w/out signatures?
From: Roy Smith (roy_at_panix.com)
Date: Thu, 06 May 2004 15:44:31 -0400
In article <firstname.lastname@example.org>,
> What's the standard way to implement polymorphic behavior in a python
> method, given that method arguments can't declare their types as
> they're being passed in, and method definitions don't have signatures?
> For instance, if I wanted to write a method that auto-detected whether
> it was being passed a string or a tuple/list, how would I do so
> without using type() to identify the parameter's type? Using type() is
> deprecated in the documentation I've read.
> Thanks in advance.
For the most part, the kind of polymorphism you see in staticly typed
languages like C++ and Java just isn't necessary in Python.
Between dynamic typing (i.e. you can take the str() of anything without
knowing what type it is) and keyword arguments, there's very little
reason to have to know what type an argument is.
The most common reason is the example you gave, where you want a
function which will operate on either an item, or a bunch of items. You
might want to be able to say:
to get rid of everybody's least favorite language, and also be able to
pass in a bunch of them:
nuke (("C++", "Java", "Perl"))
to get rid of all three at once. If you really wanted to do that, you
could define nuke something like:
def nuke (lang):
if isinstance (lang, types.TupleType):
for oneLanguage in lang:
In general, however, I try to stay away from stuff like that.