Using Multiple Constructors
aleaxit at yahoo.com
Sun Aug 5 10:43:32 CEST 2001
"Steve Holden" <sholden at holdenweb.com> wrote in message
news:GU_a7.11610$5j7.678446 at e420r-atl1.usenetserver.com...
> "Alex" <new_name at mit.edu> wrote in message
> news:etdu1zoddw4.fsf at lola-granola.mit.edu...
> > if type(initarg) == types.StringType:
> > self.Constructor1(initarg)
> What were you saying last week about people who used this construct
> to be stood up against the wall and shot (I'm paraphrasing a little here)?
I think you may be confusing the Alex who writes from mit.edu with the
Alex Martelli who writes from yahoo.com. Despite persistent rumors, we're
really two distinct people, honest!
That being said -- if there's a place anywhere for typetests, it's probably
when trying to recode in Python an existing C++ or Java program that
relies on function overloading by argument-types. Much in the same
spirit as my "assign and test" cookbook recipe:
you can't "natively" assign-and-test in Python, since = is not an
operator, but Python's powerful enough to let you use 'alien' idioms
with little conceptual overhead, in many cases.
Of course, type tests should still be coded better than type(a)==type(b)
(or even the preferable type(a) is type(b)...:-). At the very least, one
would use isinstance -- at some point in the type/class unification story,
isinstance may let you use subtypes of (e.g.) strings where equality or
identity of typeobjects would still trip you up. Probably better is however
a variation of 'accurate look-before-you-leap', see my recipe at:
although, curiously, nobody was interested enough to rate it, even
unfavourably, in the 4+ months it's been out there. It's admittedly
rather a lot of work, but the point is, getting some sort of operational
definition of what it means, for overloading purposes, for an argument
to "BE-A" string (or whatever) by determining what operations the
argument must support.
The Pythonic way is not to overload by type: use factory functions
rather than the bare constructor, and distinguish them by name. But
sometimes such recoding is too vast, it takes you too far from the
original (e.g.) C++ code that you're trying to recast into Python (for
didactical purposes or whatever). In this case, SOME sorts of type
tests may be more of a help than a hindrance -- but it's unlikely that
type(a)==type(b) can ever qualify (maybe a lintlike utility could
warn against those, suggesting at least isinstance as alternative:-).
More information about the Python-list