polymorphism in python
Roy Smith
roy at panix.com
Thu Nov 27 09:55:08 EST 2003
In article <mailman.1127.1069899957.702.python-list at python.org>,
"Robert Brewer" <fumanchu at amor.org> wrote:
> Roy Smith wrote:
> > But how often is it actually useful to do such a thing? I can't
> > remember the last time I wanted to do something like that in
> > Python.
>
> And Jay O'Connor replied:
> > Generally, if you are programming to the interface and not to
> > the class (which is what you are usually doing in OO programming,
> > or should be if your language allows it) than testing for the
> > actual type of an object is usually a no-no
>
> I find this comes up quite often in application interfaces; that is,
> points at which your code manipulates someone else's code in someone
> else's language. A prime example is forming valid SQL statements:
>
> "SELECT * FROM xyz WHERE %(Name)s = %(Value)s" % ({'Name': fieldName,
> 'Value': fieldValue})
OK, that's a fair example (and one that I've dealt with myself). In
C++, you might write a polymorphic function:
MyClass::doSqlStuff (String fieldName, int fieldValue);
MyClass::doSqlStuff (String fieldName, String fieldValue);
In Python you'd just write a single function and embed some logic to do
the right thing depending on which type you got passed:
def doSqlStuff (fieldName, fieldValue):
if type (fieldValue) == StringType: # or whatever
formatString = "'%s'"
else:
formatString = "%d"
Either way, it's basicly "if this type, execute this code, if that type,
execute some other code". The only real difference is that in something
like C++, the conditional logic is done implicitly by the compiler (with
hints from you in the form of which polymorphic methods you supply) and
in Python you write the condition explicitly. I find the explicit form
much easier to write, understand, and debug.
And don't get me started on the evils of automatic type promition and
inexact signature matching in C++.
More information about the Python-list
mailing list