polymorphism w/out signatures?
Roy Smith
roy at panix.com
Thu May 6 15:44:31 EDT 2004
In article <997a06e0.0405061128.6768676d at posting.google.com>,
pugnatio2 at yahoo.com wrote:
> 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:
nuke ("Perl")
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:
nuke (oneLanguage)
else:
whatever
In general, however, I try to stay away from stuff like that.
More information about the Python-list
mailing list